@plasius/gpu-model-runtime 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -3
- package/dist/index.cjs +636 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +118 -1
- package/dist/index.d.ts +118 -1
- package/dist/index.js +633 -0
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -507,6 +507,636 @@ function ensureHttpUrl(value) {
|
|
|
507
507
|
return url.href;
|
|
508
508
|
}
|
|
509
509
|
|
|
510
|
+
// src/model-residency.ts
|
|
511
|
+
var SHA256_PATTERN = /^[a-f0-9]{64}$/u;
|
|
512
|
+
var PARTITION_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;
|
|
513
|
+
var ModelResidencyError = class extends Error {
|
|
514
|
+
code;
|
|
515
|
+
constructor(code, message) {
|
|
516
|
+
super(message);
|
|
517
|
+
this.name = "ModelResidencyError";
|
|
518
|
+
this.code = code;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
function requireSafeNonNegativeInteger(value, name) {
|
|
522
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
523
|
+
throw new RangeError(`${name} must be a non-negative safe integer`);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
function requirePositiveSafeInteger(value, name) {
|
|
527
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
528
|
+
throw new RangeError(`${name} must be a positive safe integer`);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function requirePriority(priority) {
|
|
532
|
+
if (!Number.isFinite(priority) || priority < 0) {
|
|
533
|
+
throw new RangeError("priority must be a non-negative finite number");
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
function requireLod(lod) {
|
|
537
|
+
if (!Number.isInteger(lod) || lod < 0 || lod > 3) {
|
|
538
|
+
throw new RangeError("lod must be an integer from 0 to 3");
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function createModelResidencyKey(assetRef, lod, partitionId) {
|
|
542
|
+
if (!SHA256_PATTERN.test(assetRef.contentHash)) {
|
|
543
|
+
throw new Error("ModelAssetRef.contentHash must be a lowercase SHA-256 value");
|
|
544
|
+
}
|
|
545
|
+
requireLod(lod);
|
|
546
|
+
if (partitionId !== void 0 && !PARTITION_ID_PATTERN.test(partitionId)) {
|
|
547
|
+
throw new Error("partitionId must be a bounded runtime token");
|
|
548
|
+
}
|
|
549
|
+
return `${assetRef.contentHash}:lod${lod}:${partitionId ?? "whole"}`;
|
|
550
|
+
}
|
|
551
|
+
function closedError() {
|
|
552
|
+
return new ModelResidencyError(
|
|
553
|
+
"manager-closed",
|
|
554
|
+
"The model residency manager is closed"
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
function abortedError() {
|
|
558
|
+
return new ModelResidencyError(
|
|
559
|
+
"acquire-aborted",
|
|
560
|
+
"The model residency acquisition was aborted"
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
function signalIsAborted(signal) {
|
|
564
|
+
return signal?.aborted === true;
|
|
565
|
+
}
|
|
566
|
+
var ModelResidencyManager = class {
|
|
567
|
+
#budget;
|
|
568
|
+
#load;
|
|
569
|
+
#loadTimeoutMs;
|
|
570
|
+
#entries = /* @__PURE__ */ new Map();
|
|
571
|
+
#loadTasks = /* @__PURE__ */ new Set();
|
|
572
|
+
#disposalTasks = /* @__PURE__ */ new Set();
|
|
573
|
+
#metrics = {
|
|
574
|
+
acquireCount: 0,
|
|
575
|
+
cacheHits: 0,
|
|
576
|
+
deduplicatedAcquires: 0,
|
|
577
|
+
loadsStarted: 0,
|
|
578
|
+
loadsCompleted: 0,
|
|
579
|
+
loadsFailed: 0,
|
|
580
|
+
loadsAborted: 0,
|
|
581
|
+
loadsTimedOut: 0,
|
|
582
|
+
evictions: 0,
|
|
583
|
+
disposals: 0,
|
|
584
|
+
disposalFailures: 0
|
|
585
|
+
};
|
|
586
|
+
#nextIdentity = 1;
|
|
587
|
+
#clock = 1;
|
|
588
|
+
#inFlightLoads = 0;
|
|
589
|
+
#closed = false;
|
|
590
|
+
#admissionTail = Promise.resolve();
|
|
591
|
+
#shutdownPromise;
|
|
592
|
+
constructor(options) {
|
|
593
|
+
requirePositiveSafeInteger(
|
|
594
|
+
options.budget.maxCpuBytes,
|
|
595
|
+
"budget.maxCpuBytes"
|
|
596
|
+
);
|
|
597
|
+
requirePositiveSafeInteger(
|
|
598
|
+
options.budget.maxGpuBytes,
|
|
599
|
+
"budget.maxGpuBytes"
|
|
600
|
+
);
|
|
601
|
+
requirePositiveSafeInteger(
|
|
602
|
+
options.budget.maxInFlightLoads,
|
|
603
|
+
"budget.maxInFlightLoads"
|
|
604
|
+
);
|
|
605
|
+
if (options.loadTimeoutMs !== void 0) {
|
|
606
|
+
requirePositiveSafeInteger(options.loadTimeoutMs, "loadTimeoutMs");
|
|
607
|
+
}
|
|
608
|
+
this.#budget = Object.freeze({ ...options.budget });
|
|
609
|
+
this.#load = options.load;
|
|
610
|
+
this.#loadTimeoutMs = options.loadTimeoutMs;
|
|
611
|
+
}
|
|
612
|
+
/** Acquire one shared resource lease, loading it at most once per cache key. */
|
|
613
|
+
acquire(options) {
|
|
614
|
+
try {
|
|
615
|
+
if (this.#closed) throw closedError();
|
|
616
|
+
requirePriority(options.priority);
|
|
617
|
+
requireSafeNonNegativeInteger(
|
|
618
|
+
options.estimatedCpuBytes,
|
|
619
|
+
"estimatedCpuBytes"
|
|
620
|
+
);
|
|
621
|
+
requireSafeNonNegativeInteger(
|
|
622
|
+
options.estimatedGpuBytes,
|
|
623
|
+
"estimatedGpuBytes"
|
|
624
|
+
);
|
|
625
|
+
const key = createModelResidencyKey(
|
|
626
|
+
options.assetRef,
|
|
627
|
+
options.lod,
|
|
628
|
+
options.partitionId
|
|
629
|
+
);
|
|
630
|
+
if (signalIsAborted(options.signal)) throw abortedError();
|
|
631
|
+
this.#metrics.acquireCount += 1;
|
|
632
|
+
const existing = this.#entries.get(key);
|
|
633
|
+
if (existing !== void 0) return this.#acquireExisting(existing, options);
|
|
634
|
+
return this.#scheduleAdmission(key, options);
|
|
635
|
+
} catch (error) {
|
|
636
|
+
return Promise.reject(error);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
#acquireExisting(entry, options) {
|
|
640
|
+
this.#metrics.deduplicatedAcquires += 1;
|
|
641
|
+
if (entry.state === "resident") {
|
|
642
|
+
this.#metrics.cacheHits += 1;
|
|
643
|
+
return Promise.resolve(
|
|
644
|
+
this.#createLease(
|
|
645
|
+
entry,
|
|
646
|
+
options.priority,
|
|
647
|
+
options.pinned ?? false
|
|
648
|
+
)
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
return this.#addWaiter(entry, options);
|
|
652
|
+
}
|
|
653
|
+
#scheduleAdmission(key, options) {
|
|
654
|
+
let resolveAcquisition;
|
|
655
|
+
let rejectAcquisition;
|
|
656
|
+
const acquisition = new Promise(
|
|
657
|
+
(resolve, reject) => {
|
|
658
|
+
resolveAcquisition = resolve;
|
|
659
|
+
rejectAcquisition = reject;
|
|
660
|
+
}
|
|
661
|
+
);
|
|
662
|
+
const admission = this.#admissionTail.then(async () => {
|
|
663
|
+
if (this.#closed) throw closedError();
|
|
664
|
+
if (signalIsAborted(options.signal)) throw abortedError();
|
|
665
|
+
const existing = this.#entries.get(key);
|
|
666
|
+
if (existing !== void 0) {
|
|
667
|
+
void this.#acquireExisting(existing, options).then(
|
|
668
|
+
resolveAcquisition,
|
|
669
|
+
rejectAcquisition
|
|
670
|
+
);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
await this.#ensureCapacityForReservation(
|
|
674
|
+
options.estimatedCpuBytes,
|
|
675
|
+
options.estimatedGpuBytes
|
|
676
|
+
);
|
|
677
|
+
if (this.#closed) throw closedError();
|
|
678
|
+
if (signalIsAborted(options.signal)) throw abortedError();
|
|
679
|
+
const entry = {
|
|
680
|
+
key,
|
|
681
|
+
assetRef: options.assetRef,
|
|
682
|
+
lod: options.lod,
|
|
683
|
+
...options.partitionId === void 0 ? {} : { partitionId: options.partitionId },
|
|
684
|
+
estimatedCpuBytes: options.estimatedCpuBytes,
|
|
685
|
+
estimatedGpuBytes: options.estimatedGpuBytes,
|
|
686
|
+
queueOrder: this.#nextIdentity++,
|
|
687
|
+
state: "queued",
|
|
688
|
+
priority: options.priority,
|
|
689
|
+
retainedPriority: options.priority,
|
|
690
|
+
lastUsed: this.#clock++,
|
|
691
|
+
abandoned: false,
|
|
692
|
+
loadSlotReleased: true,
|
|
693
|
+
waiters: /* @__PURE__ */ new Map(),
|
|
694
|
+
leases: /* @__PURE__ */ new Map()
|
|
695
|
+
};
|
|
696
|
+
this.#entries.set(key, entry);
|
|
697
|
+
void this.#addWaiter(entry, options).then(
|
|
698
|
+
resolveAcquisition,
|
|
699
|
+
rejectAcquisition
|
|
700
|
+
);
|
|
701
|
+
this.#pumpQueue();
|
|
702
|
+
});
|
|
703
|
+
this.#admissionTail = admission.catch(() => void 0);
|
|
704
|
+
void admission.catch(rejectAcquisition);
|
|
705
|
+
return acquisition;
|
|
706
|
+
}
|
|
707
|
+
/** Dispose every currently unreferenced, unpinned resident cache entry. */
|
|
708
|
+
async evictUnused() {
|
|
709
|
+
const tasks = [];
|
|
710
|
+
for (const entry of this.#evictionCandidates()) {
|
|
711
|
+
tasks.push(this.#evict(entry));
|
|
712
|
+
}
|
|
713
|
+
await Promise.all(tasks);
|
|
714
|
+
}
|
|
715
|
+
/** Wait until queued/loading work and its resulting disposal have settled. */
|
|
716
|
+
async waitForIdle() {
|
|
717
|
+
await this.#admissionTail;
|
|
718
|
+
do {
|
|
719
|
+
this.#pumpQueue();
|
|
720
|
+
const tasks = [...this.#loadTasks];
|
|
721
|
+
if (tasks.length > 0) {
|
|
722
|
+
await Promise.allSettled(tasks);
|
|
723
|
+
}
|
|
724
|
+
} while (this.#loadTasks.size > 0 || this.#queuedCount() > 0);
|
|
725
|
+
await Promise.allSettled([...this.#disposalTasks]);
|
|
726
|
+
}
|
|
727
|
+
/** Abort pending work and dispose every resident or late-completing resource. */
|
|
728
|
+
shutdown() {
|
|
729
|
+
if (this.#shutdownPromise !== void 0) return this.#shutdownPromise;
|
|
730
|
+
this.#closed = true;
|
|
731
|
+
const error = closedError();
|
|
732
|
+
const disposalTasks = [];
|
|
733
|
+
for (const entry of [...this.#entries.values()]) {
|
|
734
|
+
if (entry.state === "resident") {
|
|
735
|
+
this.#entries.delete(entry.key);
|
|
736
|
+
disposalTasks.push(this.#disposeEntry(entry));
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
this.#rejectWaiters(entry, error);
|
|
740
|
+
if (entry.state === "queued") {
|
|
741
|
+
this.#entries.delete(entry.key);
|
|
742
|
+
} else {
|
|
743
|
+
this.#abandonLoadingEntry(entry, error, false);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
this.#shutdownPromise = (async () => {
|
|
747
|
+
await Promise.allSettled(disposalTasks);
|
|
748
|
+
await this.waitForIdle();
|
|
749
|
+
await Promise.allSettled([...this.#disposalTasks]);
|
|
750
|
+
})();
|
|
751
|
+
return this.#shutdownPromise;
|
|
752
|
+
}
|
|
753
|
+
/** Return immutable byte, queue, cache, and lifetime metrics. */
|
|
754
|
+
snapshot() {
|
|
755
|
+
let cpuBytes = 0;
|
|
756
|
+
let gpuBytes = 0;
|
|
757
|
+
let reservedCpuBytes = 0;
|
|
758
|
+
let reservedGpuBytes = 0;
|
|
759
|
+
let referenceCount = 0;
|
|
760
|
+
let pinnedCount = 0;
|
|
761
|
+
let residentCount = 0;
|
|
762
|
+
let pendingCount = 0;
|
|
763
|
+
const entries = [];
|
|
764
|
+
for (const entry of this.#entries.values()) {
|
|
765
|
+
const pinned = [...entry.leases.values()].some(
|
|
766
|
+
(lease) => lease.active && lease.pinned
|
|
767
|
+
);
|
|
768
|
+
const references = [...entry.leases.values()].filter(
|
|
769
|
+
(lease) => lease.active
|
|
770
|
+
).length;
|
|
771
|
+
referenceCount += references;
|
|
772
|
+
if (pinned) pinnedCount += 1;
|
|
773
|
+
if (entry.state === "resident") {
|
|
774
|
+
residentCount += 1;
|
|
775
|
+
cpuBytes += entry.loaded.cpuBytes;
|
|
776
|
+
gpuBytes += entry.loaded.gpuBytes;
|
|
777
|
+
} else {
|
|
778
|
+
pendingCount += 1;
|
|
779
|
+
reservedCpuBytes += entry.estimatedCpuBytes;
|
|
780
|
+
reservedGpuBytes += entry.estimatedGpuBytes;
|
|
781
|
+
}
|
|
782
|
+
entries.push(
|
|
783
|
+
Object.freeze({
|
|
784
|
+
key: entry.key,
|
|
785
|
+
state: entry.state,
|
|
786
|
+
priority: entry.priority,
|
|
787
|
+
references,
|
|
788
|
+
pinned,
|
|
789
|
+
cpuBytes: entry.state === "resident" ? entry.loaded.cpuBytes : entry.estimatedCpuBytes,
|
|
790
|
+
gpuBytes: entry.state === "resident" ? entry.loaded.gpuBytes : entry.estimatedGpuBytes
|
|
791
|
+
})
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
entries.sort((left, right) => left.key.localeCompare(right.key));
|
|
795
|
+
return Object.freeze({
|
|
796
|
+
...this.#budget,
|
|
797
|
+
cpuBytes,
|
|
798
|
+
gpuBytes,
|
|
799
|
+
reservedCpuBytes,
|
|
800
|
+
reservedGpuBytes,
|
|
801
|
+
residentCount,
|
|
802
|
+
pendingCount,
|
|
803
|
+
referenceCount,
|
|
804
|
+
pinnedCount,
|
|
805
|
+
inFlightLoads: this.#inFlightLoads,
|
|
806
|
+
queuedLoads: this.#queuedCount(),
|
|
807
|
+
...this.#metrics,
|
|
808
|
+
residentKeys: Object.freeze(
|
|
809
|
+
entries.filter((entry) => entry.state === "resident").map((entry) => entry.key)
|
|
810
|
+
),
|
|
811
|
+
entries: Object.freeze(entries)
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
#addWaiter(entry, options) {
|
|
815
|
+
const id = this.#nextIdentity++;
|
|
816
|
+
let resolvePromise;
|
|
817
|
+
let rejectPromise;
|
|
818
|
+
const promise = new Promise(
|
|
819
|
+
(resolve, reject) => {
|
|
820
|
+
resolvePromise = resolve;
|
|
821
|
+
rejectPromise = reject;
|
|
822
|
+
}
|
|
823
|
+
);
|
|
824
|
+
const waiter = {
|
|
825
|
+
id,
|
|
826
|
+
priority: options.priority,
|
|
827
|
+
pinned: options.pinned ?? false,
|
|
828
|
+
...options.signal === void 0 ? {} : { signal: options.signal },
|
|
829
|
+
resolve: resolvePromise,
|
|
830
|
+
reject: rejectPromise
|
|
831
|
+
};
|
|
832
|
+
if (options.signal !== void 0) {
|
|
833
|
+
waiter.onAbort = () => this.#abortWaiter(entry, waiter);
|
|
834
|
+
options.signal.addEventListener("abort", waiter.onAbort, { once: true });
|
|
835
|
+
}
|
|
836
|
+
entry.waiters.set(id, waiter);
|
|
837
|
+
entry.retainedPriority = Math.max(entry.retainedPriority, options.priority);
|
|
838
|
+
this.#recalculatePriority(entry);
|
|
839
|
+
return promise;
|
|
840
|
+
}
|
|
841
|
+
#abortWaiter(entry, waiter) {
|
|
842
|
+
entry.waiters.delete(waiter.id);
|
|
843
|
+
this.#detachWaiterSignal(waiter);
|
|
844
|
+
waiter.reject(abortedError());
|
|
845
|
+
this.#recalculatePriority(entry);
|
|
846
|
+
if (entry.waiters.size > 0) return;
|
|
847
|
+
if (entry.state === "queued") {
|
|
848
|
+
this.#entries.delete(entry.key);
|
|
849
|
+
this.#pumpQueue();
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
this.#abandonLoadingEntry(entry, abortedError(), true);
|
|
853
|
+
}
|
|
854
|
+
#createLease(entry, priority, pinned) {
|
|
855
|
+
const id = this.#nextIdentity++;
|
|
856
|
+
const record = {
|
|
857
|
+
id,
|
|
858
|
+
active: true,
|
|
859
|
+
priority,
|
|
860
|
+
pinned
|
|
861
|
+
};
|
|
862
|
+
entry.leases.set(id, record);
|
|
863
|
+
entry.retainedPriority = priority;
|
|
864
|
+
entry.lastUsed = this.#clock++;
|
|
865
|
+
this.#recalculatePriority(entry);
|
|
866
|
+
const lease = {
|
|
867
|
+
key: entry.key,
|
|
868
|
+
assetRef: entry.assetRef,
|
|
869
|
+
lod: entry.lod,
|
|
870
|
+
...entry.partitionId === void 0 ? {} : { partitionId: entry.partitionId },
|
|
871
|
+
resource: entry.loaded.resource,
|
|
872
|
+
release: () => {
|
|
873
|
+
if (!record.active) return;
|
|
874
|
+
record.active = false;
|
|
875
|
+
entry.leases.delete(id);
|
|
876
|
+
entry.lastUsed = this.#clock++;
|
|
877
|
+
this.#recalculatePriority(entry);
|
|
878
|
+
},
|
|
879
|
+
setPriority: (nextPriority) => {
|
|
880
|
+
if (!record.active || this.#entries.get(entry.key) !== entry) return;
|
|
881
|
+
requirePriority(nextPriority);
|
|
882
|
+
record.priority = nextPriority;
|
|
883
|
+
entry.retainedPriority = nextPriority;
|
|
884
|
+
entry.lastUsed = this.#clock++;
|
|
885
|
+
this.#recalculatePriority(entry);
|
|
886
|
+
},
|
|
887
|
+
setPinned: (nextPinned) => {
|
|
888
|
+
if (!record.active || this.#entries.get(entry.key) !== entry) return;
|
|
889
|
+
record.pinned = nextPinned;
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
return Object.freeze(lease);
|
|
893
|
+
}
|
|
894
|
+
#recalculatePriority(entry) {
|
|
895
|
+
let priority = entry.retainedPriority;
|
|
896
|
+
for (const waiter of entry.waiters.values()) {
|
|
897
|
+
priority = Math.max(priority, waiter.priority);
|
|
898
|
+
}
|
|
899
|
+
for (const lease of entry.leases.values()) {
|
|
900
|
+
priority = Math.max(priority, lease.priority);
|
|
901
|
+
}
|
|
902
|
+
entry.priority = priority;
|
|
903
|
+
}
|
|
904
|
+
#pumpQueue() {
|
|
905
|
+
if (this.#closed) return;
|
|
906
|
+
while (this.#inFlightLoads < this.#budget.maxInFlightLoads) {
|
|
907
|
+
const candidate = [...this.#entries.values()].filter(
|
|
908
|
+
(entry) => entry.state === "queued" && !entry.abandoned && entry.waiters.size > 0
|
|
909
|
+
).sort(
|
|
910
|
+
(left, right) => right.priority - left.priority || left.queueOrder - right.queueOrder
|
|
911
|
+
)[0];
|
|
912
|
+
if (candidate === void 0) return;
|
|
913
|
+
this.#startLoad(candidate);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
#startLoad(entry) {
|
|
917
|
+
entry.state = "loading";
|
|
918
|
+
entry.loadSlotReleased = false;
|
|
919
|
+
entry.controller = new AbortController();
|
|
920
|
+
this.#inFlightLoads += 1;
|
|
921
|
+
this.#metrics.loadsStarted += 1;
|
|
922
|
+
if (this.#loadTimeoutMs !== void 0) {
|
|
923
|
+
entry.timeout = setTimeout(() => {
|
|
924
|
+
this.#metrics.loadsTimedOut += 1;
|
|
925
|
+
this.#abandonLoadingEntry(
|
|
926
|
+
entry,
|
|
927
|
+
new ModelResidencyError(
|
|
928
|
+
"load-timeout",
|
|
929
|
+
`Model load exceeded ${this.#loadTimeoutMs} ms`
|
|
930
|
+
),
|
|
931
|
+
true
|
|
932
|
+
);
|
|
933
|
+
}, this.#loadTimeoutMs);
|
|
934
|
+
}
|
|
935
|
+
let adapterPromise;
|
|
936
|
+
try {
|
|
937
|
+
adapterPromise = this.#load({
|
|
938
|
+
assetRef: entry.assetRef,
|
|
939
|
+
lod: entry.lod,
|
|
940
|
+
...entry.partitionId === void 0 ? {} : { partitionId: entry.partitionId },
|
|
941
|
+
priority: entry.priority,
|
|
942
|
+
signal: entry.controller.signal
|
|
943
|
+
});
|
|
944
|
+
} catch (error) {
|
|
945
|
+
adapterPromise = Promise.reject(error);
|
|
946
|
+
}
|
|
947
|
+
const task = Promise.resolve(adapterPromise).then((result) => this.#completeLoad(entry, result)).catch((error) => this.#failLoad(entry, error)).finally(() => {
|
|
948
|
+
if (entry.timeout !== void 0) clearTimeout(entry.timeout);
|
|
949
|
+
entry.timeout = void 0;
|
|
950
|
+
entry.controller = void 0;
|
|
951
|
+
this.#releaseLoadSlot(entry);
|
|
952
|
+
entry.loadTask = void 0;
|
|
953
|
+
});
|
|
954
|
+
entry.loadTask = task;
|
|
955
|
+
this.#loadTasks.add(task);
|
|
956
|
+
}
|
|
957
|
+
async #completeLoad(entry, result) {
|
|
958
|
+
if (entry.abandoned) {
|
|
959
|
+
await this.#disposeLoaded(result);
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
try {
|
|
963
|
+
this.#validateLoadedResource(entry, result);
|
|
964
|
+
const evictions = this.#ensureCapacityForLoadedResult(entry, result);
|
|
965
|
+
await Promise.all(evictions);
|
|
966
|
+
} catch (error) {
|
|
967
|
+
await this.#disposeLoaded(result);
|
|
968
|
+
this.#entries.delete(entry.key);
|
|
969
|
+
this.#rejectWaiters(entry, error);
|
|
970
|
+
this.#metrics.loadsFailed += 1;
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
entry.state = "resident";
|
|
974
|
+
entry.loaded = result;
|
|
975
|
+
entry.lastUsed = this.#clock++;
|
|
976
|
+
this.#metrics.loadsCompleted += 1;
|
|
977
|
+
const waiters = [...entry.waiters.values()];
|
|
978
|
+
entry.waiters.clear();
|
|
979
|
+
for (const waiter of waiters) {
|
|
980
|
+
this.#detachWaiterSignal(waiter);
|
|
981
|
+
waiter.resolve(this.#createLease(entry, waiter.priority, waiter.pinned));
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
#failLoad(entry, error) {
|
|
985
|
+
if (entry.abandoned) return;
|
|
986
|
+
this.#entries.delete(entry.key);
|
|
987
|
+
this.#metrics.loadsFailed += 1;
|
|
988
|
+
this.#rejectWaiters(entry, error);
|
|
989
|
+
}
|
|
990
|
+
#abandonLoadingEntry(entry, error, rejectWaiters) {
|
|
991
|
+
entry.abandoned = true;
|
|
992
|
+
this.#metrics.loadsAborted += 1;
|
|
993
|
+
if (entry.timeout !== void 0) clearTimeout(entry.timeout);
|
|
994
|
+
entry.timeout = void 0;
|
|
995
|
+
this.#entries.delete(entry.key);
|
|
996
|
+
if (rejectWaiters) this.#rejectWaiters(entry, error);
|
|
997
|
+
entry.controller?.abort(error);
|
|
998
|
+
this.#releaseLoadSlot(entry);
|
|
999
|
+
}
|
|
1000
|
+
#releaseLoadSlot(entry) {
|
|
1001
|
+
if (entry.loadSlotReleased) return;
|
|
1002
|
+
entry.loadSlotReleased = true;
|
|
1003
|
+
this.#inFlightLoads -= 1;
|
|
1004
|
+
this.#loadTasks.delete(entry.loadTask);
|
|
1005
|
+
this.#pumpQueue();
|
|
1006
|
+
}
|
|
1007
|
+
#rejectWaiters(entry, error) {
|
|
1008
|
+
const waiters = [...entry.waiters.values()];
|
|
1009
|
+
entry.waiters.clear();
|
|
1010
|
+
for (const waiter of waiters) {
|
|
1011
|
+
this.#detachWaiterSignal(waiter);
|
|
1012
|
+
waiter.reject(error);
|
|
1013
|
+
}
|
|
1014
|
+
this.#recalculatePriority(entry);
|
|
1015
|
+
}
|
|
1016
|
+
#detachWaiterSignal(waiter) {
|
|
1017
|
+
if (waiter.signal !== void 0 && waiter.onAbort !== void 0) {
|
|
1018
|
+
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
|
1019
|
+
}
|
|
1020
|
+
waiter.onAbort = void 0;
|
|
1021
|
+
}
|
|
1022
|
+
#validateLoadedResource(entry, result) {
|
|
1023
|
+
if (result === null || typeof result !== "object") {
|
|
1024
|
+
throw new ModelResidencyError(
|
|
1025
|
+
"invalid-load-result",
|
|
1026
|
+
"The model loader returned an invalid resource"
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
if (typeof result.dispose !== "function") {
|
|
1030
|
+
throw new ModelResidencyError(
|
|
1031
|
+
"invalid-load-result",
|
|
1032
|
+
"The model loader must return a disposer"
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
requireSafeNonNegativeInteger(result.cpuBytes, "loaded.cpuBytes");
|
|
1036
|
+
requireSafeNonNegativeInteger(result.gpuBytes, "loaded.gpuBytes");
|
|
1037
|
+
if (result.contentHash !== entry.assetRef.contentHash) {
|
|
1038
|
+
throw new ModelResidencyError(
|
|
1039
|
+
"content-hash-mismatch",
|
|
1040
|
+
"The loaded model content hash does not match its canonical reference"
|
|
1041
|
+
);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
async #ensureCapacityForReservation(cpuBytes, gpuBytes) {
|
|
1045
|
+
if (cpuBytes > this.#budget.maxCpuBytes || gpuBytes > this.#budget.maxGpuBytes) {
|
|
1046
|
+
throw this.#budgetError();
|
|
1047
|
+
}
|
|
1048
|
+
let usage = this.#totalAccountedBytes();
|
|
1049
|
+
for (const candidate of this.#evictionCandidates()) {
|
|
1050
|
+
if (usage.cpu + cpuBytes <= this.#budget.maxCpuBytes && usage.gpu + gpuBytes <= this.#budget.maxGpuBytes) {
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
await this.#evict(candidate);
|
|
1054
|
+
usage = this.#totalAccountedBytes();
|
|
1055
|
+
}
|
|
1056
|
+
if (usage.cpu + cpuBytes > this.#budget.maxCpuBytes || usage.gpu + gpuBytes > this.#budget.maxGpuBytes) {
|
|
1057
|
+
throw this.#budgetError();
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
#ensureCapacityForLoadedResult(loadingEntry, result) {
|
|
1061
|
+
const usage = this.#totalAccountedBytes();
|
|
1062
|
+
usage.cpu += result.cpuBytes - loadingEntry.estimatedCpuBytes;
|
|
1063
|
+
usage.gpu += result.gpuBytes - loadingEntry.estimatedGpuBytes;
|
|
1064
|
+
const disposals = [];
|
|
1065
|
+
for (const candidate of this.#evictionCandidates()) {
|
|
1066
|
+
if (usage.cpu <= this.#budget.maxCpuBytes && usage.gpu <= this.#budget.maxGpuBytes) {
|
|
1067
|
+
return disposals;
|
|
1068
|
+
}
|
|
1069
|
+
usage.cpu -= candidate.loaded.cpuBytes;
|
|
1070
|
+
usage.gpu -= candidate.loaded.gpuBytes;
|
|
1071
|
+
disposals.push(this.#evict(candidate));
|
|
1072
|
+
}
|
|
1073
|
+
if (usage.cpu > this.#budget.maxCpuBytes || usage.gpu > this.#budget.maxGpuBytes) {
|
|
1074
|
+
throw this.#budgetError();
|
|
1075
|
+
}
|
|
1076
|
+
return disposals;
|
|
1077
|
+
}
|
|
1078
|
+
#budgetError() {
|
|
1079
|
+
return new ModelResidencyError(
|
|
1080
|
+
"budget-exceeded",
|
|
1081
|
+
"Pinned, referenced, or pending models leave insufficient residency budget"
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
#totalAccountedBytes() {
|
|
1085
|
+
let cpu = 0;
|
|
1086
|
+
let gpu = 0;
|
|
1087
|
+
for (const entry of this.#entries.values()) {
|
|
1088
|
+
if (entry.state === "resident") {
|
|
1089
|
+
cpu += entry.loaded.cpuBytes;
|
|
1090
|
+
gpu += entry.loaded.gpuBytes;
|
|
1091
|
+
} else {
|
|
1092
|
+
cpu += entry.estimatedCpuBytes;
|
|
1093
|
+
gpu += entry.estimatedGpuBytes;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
return { cpu, gpu };
|
|
1097
|
+
}
|
|
1098
|
+
#evictionCandidates() {
|
|
1099
|
+
return [...this.#entries.values()].filter(
|
|
1100
|
+
(entry) => entry.state === "resident" && entry.leases.size === 0
|
|
1101
|
+
).sort(
|
|
1102
|
+
(left, right) => left.priority - right.priority || left.lastUsed - right.lastUsed
|
|
1103
|
+
);
|
|
1104
|
+
}
|
|
1105
|
+
#evict(entry) {
|
|
1106
|
+
this.#entries.delete(entry.key);
|
|
1107
|
+
this.#metrics.evictions += 1;
|
|
1108
|
+
return this.#disposeEntry(entry);
|
|
1109
|
+
}
|
|
1110
|
+
#disposeEntry(entry) {
|
|
1111
|
+
const result = entry.loaded;
|
|
1112
|
+
entry.loaded = void 0;
|
|
1113
|
+
return this.#disposeLoaded(result);
|
|
1114
|
+
}
|
|
1115
|
+
#disposeLoaded(result) {
|
|
1116
|
+
this.#metrics.disposals += 1;
|
|
1117
|
+
let disposal;
|
|
1118
|
+
try {
|
|
1119
|
+
disposal = Promise.resolve(result.dispose());
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
disposal = Promise.reject(error);
|
|
1122
|
+
}
|
|
1123
|
+
const tracked = disposal.catch(() => {
|
|
1124
|
+
this.#metrics.disposalFailures += 1;
|
|
1125
|
+
}).finally(() => {
|
|
1126
|
+
this.#disposalTasks.delete(tracked);
|
|
1127
|
+
});
|
|
1128
|
+
this.#disposalTasks.add(tracked);
|
|
1129
|
+
return tracked;
|
|
1130
|
+
}
|
|
1131
|
+
#queuedCount() {
|
|
1132
|
+
let count = 0;
|
|
1133
|
+
for (const entry of this.#entries.values()) {
|
|
1134
|
+
if (entry.state === "queued") count += 1;
|
|
1135
|
+
}
|
|
1136
|
+
return count;
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
|
|
510
1140
|
// src/index.ts
|
|
511
1141
|
var packageName = "@plasius/gpu-model-runtime";
|
|
512
1142
|
var packageBootstrap = Object.freeze({
|
|
@@ -517,9 +1147,12 @@ var packageBootstrap = Object.freeze({
|
|
|
517
1147
|
export {
|
|
518
1148
|
AdapterRegistry,
|
|
519
1149
|
MemoryModelCache,
|
|
1150
|
+
ModelResidencyError,
|
|
1151
|
+
ModelResidencyManager,
|
|
520
1152
|
ModelRuntime,
|
|
521
1153
|
PackageResourceResolver,
|
|
522
1154
|
createModelCacheKey,
|
|
1155
|
+
createModelResidencyKey,
|
|
523
1156
|
defaultSleep,
|
|
524
1157
|
fetchResource,
|
|
525
1158
|
packageBootstrap,
|