omnius 1.0.923 → 1.0.925
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/dist/{providerRegistry.d.ts → _types/backend-vllm/providerRegistry.d.ts} +0 -1
- package/dist/_types/backend-vllm/types.d.ts +209 -0
- package/dist/_types/execution/av/media-capability.d.ts +94 -0
- package/dist/_types/execution/delegation-contract.d.ts +102 -0
- package/dist/_types/execution/evidence.d.ts +68 -0
- package/dist/_types/execution/html-source-evidence.d.ts +65 -0
- package/dist/_types/execution/mcp/types.d.ts +169 -0
- package/dist/_types/execution/mutation-contract.d.ts +102 -0
- package/dist/_types/execution/nol/artifacts.d.ts +39 -0
- package/dist/_types/execution/nol/checkpoint-edits.d.ts +98 -0
- package/dist/_types/execution/nol/distributions.d.ts +128 -0
- package/dist/_types/execution/nol/gguf-checkpoint-edits.d.ts +194 -0
- package/dist/_types/execution/nol/gguf-control-reader.d.ts +224 -0
- package/dist/_types/execution/nol/lora-exports.d.ts +129 -0
- package/dist/_types/execution/nol/neuronary.d.ts +212 -0
- package/dist/_types/execution/nol/pytorch-control-reader.d.ts +143 -0
- package/dist/_types/execution/nol/qwen35-head-sites.d.ts +61 -0
- package/dist/_types/execution/nol/worker-assets.d.ts +82 -0
- package/dist/_types/execution/nol/worker-protocol.d.ts +94 -0
- package/dist/_types/execution/page-content-source.d.ts +40 -0
- package/dist/_types/execution/rapid-computer-use/artifact-store.d.ts +21 -0
- package/dist/_types/execution/rapid-computer-use/contracts.d.ts +320 -0
- package/dist/_types/execution/rapid-computer-use/decision.d.ts +70 -0
- package/dist/_types/execution/rapid-computer-use/desktop-verification.d.ts +23 -0
- package/dist/_types/execution/rapid-computer-use/geometry.d.ts +57 -0
- package/dist/_types/execution/rapid-computer-use/planner.d.ts +78 -0
- package/dist/_types/execution/rapid-computer-use/trace.d.ts +80 -0
- package/dist/_types/execution/rapid-computer-use/visual.d.ts +48 -0
- package/dist/_types/execution/shell-runs.d.ts +78 -0
- package/dist/_types/execution/streamed-web-source.d.ts +64 -0
- package/dist/_types/execution/tools/browser-page-fallback.d.ts +25 -0
- package/dist/_types/execution/tools/network-egress-policy.d.ts +30 -0
- package/dist/_types/execution/tools/pdf-native-tables.d.ts +46 -0
- package/dist/_types/execution/tools/todo-store.d.ts +133 -0
- package/dist/_types/execution/tools/web-fetch.d.ts +57 -0
- package/dist/_types/execution/tools/workboard.d.ts +1223 -0
- package/dist/_types/execution/types.d.ts +549 -0
- package/dist/_types/execution/web-source.d.ts +14 -0
- package/dist/_types/memory/artifactReviewSourceIndex.d.ts +133 -0
- package/dist/_types/memory/contextMemoryLedger.d.ts +213 -0
- package/dist/_types/memory/db.d.ts +12 -0
- package/dist/_types/memory/embeddings.d.ts +36 -0
- package/dist/_types/memory/immutableEvidenceStore.d.ts +165 -0
- package/dist/_types/memory/memoryIngestion.d.ts +65 -0
- package/dist/_types/memory/memoryTypes.d.ts +312 -0
- package/dist/_types/memory/sourceCorpusStore.d.ts +331 -0
- package/dist/_types/memory/structuredMemoryStore.d.ts +105 -0
- package/dist/_types/memory/unifiedMemoryStore.d.ts +127 -0
- package/dist/_types/memory/virtualMemory.d.ts +187 -0
- package/dist/_types/orchestrator/agentic-page-content-receipt.d.ts +20 -0
- package/dist/_types/orchestrator/agentic-web-fetch-receipt.d.ts +20 -0
- package/dist/_types/orchestrator/agenticRunner.d.ts +5219 -0
- package/dist/_types/orchestrator/app-state.d.ts +171 -0
- package/dist/_types/orchestrator/artifactClaimCritic.d.ts +63 -0
- package/dist/_types/orchestrator/artifactQuality.d.ts +15 -0
- package/dist/_types/orchestrator/artifactSemanticIntegrity.d.ts +203 -0
- package/dist/_types/orchestrator/canonical-context-projection.d.ts +254 -0
- package/dist/_types/orchestrator/canonical-source-body-projection.d.ts +51 -0
- package/dist/_types/orchestrator/completion-review-pending.d.ts +24 -0
- package/dist/_types/orchestrator/completionContract.d.ts +103 -0
- package/dist/_types/orchestrator/completionFinalization.d.ts +224 -0
- package/dist/_types/orchestrator/completionLedger.d.ts +429 -0
- package/dist/_types/orchestrator/completionReadiness.d.ts +234 -0
- package/dist/_types/orchestrator/context-admission.d.ts +93 -0
- package/dist/_types/orchestrator/context-dump-retention.d.ts +25 -0
- package/dist/_types/orchestrator/context-fabric.d.ts +133 -0
- package/dist/_types/orchestrator/contextEngine.d.ts +68 -0
- package/dist/_types/orchestrator/contextWindowDump.d.ts +327 -0
- package/dist/_types/orchestrator/convergence-breaker.d.ts +225 -0
- package/dist/_types/orchestrator/convergence-progress.d.ts +66 -0
- package/dist/_types/orchestrator/deliveryCoverage.d.ts +181 -0
- package/dist/_types/orchestrator/document-persistence-goal-binding.d.ts +106 -0
- package/dist/_types/orchestrator/durable-document-worker.d.ts +85 -0
- package/dist/_types/orchestrator/evidenceBranch.d.ts +291 -0
- package/dist/_types/orchestrator/expected-inference-response.d.ts +55 -0
- package/dist/_types/orchestrator/expectedOutcomeContract.d.ts +58 -0
- package/dist/_types/orchestrator/failure-taxonomy.d.ts +36 -0
- package/dist/_types/orchestrator/focusSupervisor.d.ts +436 -0
- package/dist/_types/orchestrator/forced-update-requirement-recovery.d.ts +105 -0
- package/dist/_types/orchestrator/hooks.d.ts +100 -0
- package/dist/_types/orchestrator/inference-pressure.d.ts +61 -0
- package/dist/_types/orchestrator/integrationClosure.d.ts +89 -0
- package/dist/_types/orchestrator/interruption-lifecycle.d.ts +154 -0
- package/dist/_types/orchestrator/live-memory-passages.d.ts +51 -0
- package/dist/_types/orchestrator/liveVirtualContext.d.ts +84 -0
- package/dist/_types/orchestrator/memory-compiler.d.ts +254 -0
- package/dist/_types/orchestrator/memory-consolidation.d.ts +134 -0
- package/dist/_types/orchestrator/model-router.d.ts +17 -0
- package/dist/_types/orchestrator/modelResponseDiagnostics.d.ts +71 -0
- package/dist/_types/orchestrator/nativeRequirementAmendment.d.ts +63 -0
- package/dist/_types/orchestrator/nol/coordinator.d.ts +204 -0
- package/dist/_types/orchestrator/nol/datasets.d.ts +58 -0
- package/dist/_types/orchestrator/nol/discovery.d.ts +286 -0
- package/dist/_types/orchestrator/nol/evaluation.d.ts +59 -0
- package/dist/_types/orchestrator/nol/model-validation.d.ts +198 -0
- package/dist/_types/orchestrator/nol/statistics.d.ts +142 -0
- package/dist/_types/orchestrator/nol/store.d.ts +133 -0
- package/dist/_types/orchestrator/nol/variant-registry.d.ts +292 -0
- package/dist/_types/orchestrator/ollama-context-policy.d.ts +34 -0
- package/dist/_types/orchestrator/personality.d.ts +66 -0
- package/dist/_types/orchestrator/prompt-cache.d.ts +24 -0
- package/dist/_types/orchestrator/remote-inference-fallback.d.ts +224 -0
- package/dist/_types/orchestrator/remote-inference-policy.d.ts +58 -0
- package/dist/_types/orchestrator/request-budget.d.ts +75 -0
- package/dist/_types/orchestrator/requirementCoverage.d.ts +69 -0
- package/dist/_types/orchestrator/reviewedInterpretation.d.ts +111 -0
- package/dist/_types/orchestrator/runEvents.d.ts +115 -0
- package/dist/_types/orchestrator/runtime-rollout.d.ts +63 -0
- package/dist/_types/orchestrator/semanticVerification.d.ts +135 -0
- package/dist/_types/orchestrator/source-wide-extraction.d.ts +202 -0
- package/dist/_types/orchestrator/steeringIntake.d.ts +123 -0
- package/dist/_types/orchestrator/structured-memory-extraction-worker.d.ts +89 -0
- package/dist/_types/orchestrator/structuredMemoryInference.d.ts +62 -0
- package/dist/_types/orchestrator/successful-procedure-memory.d.ts +127 -0
- package/dist/_types/orchestrator/supportedAnswer.d.ts +68 -0
- package/dist/_types/orchestrator/taskEffectEvidence.d.ts +38 -0
- package/dist/_types/orchestrator/taskExecutionSnapshot.d.ts +67 -0
- package/dist/_types/orchestrator/taskObjective.d.ts +310 -0
- package/dist/_types/orchestrator/taskObjectiveContinuation.d.ts +134 -0
- package/dist/_types/orchestrator/taskRequirementReview.d.ts +246 -0
- package/dist/_types/orchestrator/taskRequirements.d.ts +80 -0
- package/dist/_types/orchestrator/taskSemanticAdmission.d.ts +159 -0
- package/dist/_types/orchestrator/taskWorkDelegation.d.ts +147 -0
- package/dist/_types/orchestrator/taskWorkPlan.d.ts +177 -0
- package/dist/_types/orchestrator/telegram-passive-history.d.ts +42 -0
- package/dist/_types/orchestrator/terminalTaskReport.d.ts +91 -0
- package/dist/_types/orchestrator/todoObservability.d.ts +147 -0
- package/dist/_types/orchestrator/tool-exposure-policy.d.ts +100 -0
- package/dist/_types/orchestrator/trajectory-checkpoint.d.ts +159 -0
- package/dist/_types/orchestrator/types.d.ts +185 -0
- package/dist/_types/schemas/dispatch.d.ts +53 -0
- package/dist/_types/schemas/feature-workflow.d.ts +362 -0
- package/dist/_types/schemas/messages.d.ts +15 -0
- package/dist/_types/schemas/nol-assets.d.ts +955 -0
- package/dist/_types/schemas/nol-json.d.ts +2 -0
- package/dist/_types/schemas/nol.d.ts +3995 -0
- package/dist/_types/schemas/patch.d.ts +47 -0
- package/dist/_types/schemas/plan.d.ts +47 -0
- package/dist/_types/schemas/repoProfile.d.ts +116 -0
- package/dist/_types/schemas/retrieval.d.ts +44 -0
- package/dist/_types/schemas/task.d.ts +57 -0
- package/dist/_types/schemas/tools.d.ts +16 -0
- package/dist/_types/schemas/verification.d.ts +31 -0
- package/dist/api/py-embed.js +3353 -1829
- package/dist/assets/nol-checkpoint-editor.py +701 -0
- package/dist/assets/nol-gguf-checkpoint-editor.py +785 -0
- package/dist/assets/nol-gguf-control-reader.py +428 -0
- package/dist/assets/nol-gne-tools-worker.py +425 -0
- package/dist/assets/nol-gne-worker.py +1081 -0
- package/dist/assets/nol-lora-exporter.py +349 -0
- package/dist/assets/nol-pytorch-control-reader.py +470 -0
- package/dist/assets/nol-transformers-nnsight-worker.py +512 -0
- package/dist/assets/nol-transformers-peft-validation-worker.py +385 -0
- package/dist/assets/nol-transformers-peft-worker.py +488 -0
- package/dist/assets/nol-transformers-research-worker.py +472 -0
- package/dist/assets/nol-transformers-worker.py +920 -0
- package/dist/assets/nol-vllm-owned-worker.py +803 -0
- package/dist/assets/nol-vllm-runtime.py +695 -0
- package/dist/assets/nol-vllm-tokenizer.py +93 -0
- package/dist/assets/nol-vllm-worker.py +201 -0
- package/dist/computer-use/configured-planner.d.ts +37 -0
- package/dist/computer-use/configured-point.d.ts +35 -0
- package/dist/computer-use/host-session.d.ts +60 -0
- package/dist/computer-use/runner-ui-port.d.ts +37 -0
- package/dist/computer-use/session-review.d.ts +14 -0
- package/dist/computer-use/task-spec.d.ts +84 -0
- package/dist/discovery.d.ts +16 -2
- package/dist/index.js +2 -2
- package/dist/library.d.ts +94 -10
- package/dist/library.js +144003 -87414
- package/dist/memory-maintenance-worker.js +1676 -511
- package/dist/nol/cpu-control-reader-profile.d.ts +93 -0
- package/dist/nol/cpu-control-reader-service.d.ts +87 -0
- package/dist/nol/cuda-lease.d.ts +111 -0
- package/dist/nol/cuda-mutations.d.ts +34 -0
- package/dist/nol/export-runtime-config.d.ts +114 -0
- package/dist/nol/export-service.d.ts +143 -0
- package/dist/nol/facade.d.ts +147 -0
- package/dist/nol/gguf-cpu-control-reader-profile.d.ts +106 -0
- package/dist/nol/gguf-cpu-control-reader-service.d.ts +91 -0
- package/dist/nol/gguf-model-control-verifier.d.ts +120 -0
- package/dist/nol/gguf-parameter-inventory.d.ts +28 -0
- package/dist/nol/gne-adapter.d.ts +134 -0
- package/dist/nol/gne-agent-evaluation.d.ts +84 -0
- package/dist/nol/gne-profile.d.ts +124 -0
- package/dist/nol/gne-tools-profile.d.ts +148 -0
- package/dist/nol/gne-tools-transport.d.ts +194 -0
- package/dist/nol/model-actions.d.ts +662 -0
- package/dist/nol/model-control-verifier.d.ts +135 -0
- package/dist/nol/model-json-scorer.d.ts +13 -0
- package/dist/nol/model-runtime-config.d.ts +830 -0
- package/dist/nol/model-serving.d.ts +130 -0
- package/dist/nol/model-subject-adapter.d.ts +72 -0
- package/dist/nol/model-validation-factory.d.ts +113 -0
- package/dist/nol/neuronary-catalog.d.ts +130 -0
- package/dist/nol/orphan-custody.d.ts +72 -0
- package/dist/nol/peft-conformance.d.ts +48 -0
- package/dist/nol/peft-control-types.d.ts +137 -0
- package/dist/nol/peft-control-verifier.d.ts +8 -0
- package/dist/nol/peft-model-actions.d.ts +41 -0
- package/dist/nol/peft-model-authority.d.ts +146 -0
- package/dist/nol/peft-model-controls.d.ts +20 -0
- package/dist/nol/peft-model-host.d.ts +47 -0
- package/dist/nol/peft-model-profile.d.ts +161 -0
- package/dist/nol/peft-model-runtime-config.d.ts +174 -0
- package/dist/nol/peft-model-subject-adapter.d.ts +36 -0
- package/dist/nol/peft-validation.d.ts +105 -0
- package/dist/nol/persistent-parameter-inventory.d.ts +32 -0
- package/dist/nol/runtime.d.ts +100 -0
- package/dist/nol/sqlite-store.d.ts +80 -0
- package/dist/nol/transformers-adapter.d.ts +119 -0
- package/dist/nol/transformers-nnsight.d.ts +87 -0
- package/dist/nol/transformers-peft.d.ts +107 -0
- package/dist/nol/transformers-research.d.ts +114 -0
- package/dist/nol/variant-service.d.ts +143 -0
- package/dist/nol/variant-store.d.ts +51 -0
- package/dist/nol/vllm-actions.d.ts +774 -0
- package/dist/nol/vllm-adapter.d.ts +1473 -0
- package/dist/nol/vllm-authority.d.ts +55 -0
- package/dist/nol/vllm-conformance.d.ts +662 -0
- package/dist/nol/vllm-profile.d.ts +850 -0
- package/dist/nol/vllm-protocol.d.ts +1505 -0
- package/dist/nol/vllm-runtime-config.d.ts +120 -0
- package/dist/nol/vllm-runtime.d.ts +34 -0
- package/dist/nol/vllm-startup.d.ts +235 -0
- package/dist/omni-setup-worker.js +3433 -1909
- package/dist/service-version.d.ts +0 -1
- package/dist/tui/async-process.d.ts +27 -0
- package/dist/tui/native/worker.js +3 -1
- package/dist/tui/telegram-action-session-registry.d.ts +136 -0
- package/dist/tui/telegram-cognition-queue.d.ts +154 -0
- package/dist/tui/telegram-context-packet-v2.d.ts +99 -0
- package/dist/tui/telegram-input-ownership.d.ts +78 -0
- package/dist/tui/telegram-turn-contract-v2.d.ts +62 -0
- package/dist/update-worker-runtime.js +4216 -2603
- package/docs/DISCOVERY.json +389 -0
- package/docs/DISCOVERY.md +4 -0
- package/npm-shrinkwrap.json +28 -12
- package/package.json +3 -2
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Pinned, unmerged PEFT extension of the frozen NOL Transformers worker.
|
|
3
|
+
|
|
4
|
+
Startup and inspect are stdlib-only. CUDA/model work requires the explicit load
|
|
5
|
+
command, exact host-owned scope and placement confirmation. Reports are observed
|
|
6
|
+
facts, never scientific, promotion, broker or full-base-memory attestations.
|
|
7
|
+
"""
|
|
8
|
+
import hashlib
|
|
9
|
+
import importlib.metadata
|
|
10
|
+
import importlib.util
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import re
|
|
16
|
+
import struct
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
sys.dont_write_bytecode = True
|
|
20
|
+
VERSION = "omnius.nol.transformers-peft.v2"
|
|
21
|
+
BASE_SHA = "ea1950abcceda7d76c5fb54c3b10a73d5756cd947149d4b3b6d7be83ae12ebc0"
|
|
22
|
+
PEFT_VERSION = "0.21.2"
|
|
23
|
+
PEFT_WHEEL_SHA = "106ab6077ff72c54d21577f9af5970e34bac7582cb14209f7b2b511e322a4eae"
|
|
24
|
+
PEFT_FILES = {
|
|
25
|
+
"peft_model.py": "d22a1c50dea7a046ce28e71a79dfc20b1d96a2d238a9b457be6a88b6068e04d5",
|
|
26
|
+
"tuners/lora/layer.py": "9a2688af69fd16cef94fdb08ab0e973b37d7b2a672e64ba2057a01df7e98b7d8",
|
|
27
|
+
"tuners/lora/model.py": "321964321e14ca0d9b4d81c4debcb486bae02193a576755b116ce35252e33555",
|
|
28
|
+
"utils/save_and_load.py": "6afbb53933550a401a19e883ba888f4818eb507f64306f5619a56316b598289b",
|
|
29
|
+
}
|
|
30
|
+
BASE_PATH = Path(__file__).resolve().parent / "nol-transformers-worker.py"
|
|
31
|
+
if BASE_PATH.is_symlink() or hashlib.sha256(BASE_PATH.read_bytes()).hexdigest() != BASE_SHA:
|
|
32
|
+
raise RuntimeError("Frozen Transformers base asset identity changed")
|
|
33
|
+
spec = importlib.util.spec_from_file_location("_nol_peft_frozen_base", BASE_PATH)
|
|
34
|
+
base = importlib.util.module_from_spec(spec)
|
|
35
|
+
spec.loader.exec_module(base)
|
|
36
|
+
require, fields, integer, number = base.require, base.fields, base.integer, base.number
|
|
37
|
+
Rejected = base.Rejected
|
|
38
|
+
ORIGINAL_BUILD = base.runtime_info
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def source_pin():
|
|
42
|
+
distribution = importlib.metadata.distribution("peft")
|
|
43
|
+
require(distribution.version == PEFT_VERSION, "Unreviewed PEFT version", "UNSUPPORTED")
|
|
44
|
+
files = {}
|
|
45
|
+
for name, expected in PEFT_FILES.items():
|
|
46
|
+
actual = base.hash_file(Path(distribution.locate_file("peft/" + name)), 4194304)
|
|
47
|
+
require(actual["sha256"] == expected, "Reviewed PEFT source changed", "IDENTITY")
|
|
48
|
+
files[name] = actual
|
|
49
|
+
return {"version": PEFT_VERSION, "reviewedWheelSha256": PEFT_WHEEL_SHA, "files": files}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def runtime_info(lock_path=None, hash_runtime=False, max_bytes=34359738368):
|
|
53
|
+
# ORIGINAL_BUILD hashes the code/native inventory of every installed package,
|
|
54
|
+
# including all PEFT modules, not merely these reviewed loading-path pins.
|
|
55
|
+
info = ORIGINAL_BUILD(lock_path, hash_runtime, max_bytes)
|
|
56
|
+
info.update(schema="omnius.nol.transformers-peft-build.v2", workerVersion=VERSION,
|
|
57
|
+
workerSha256=base.hash_file(Path(__file__).resolve())["sha256"],
|
|
58
|
+
baseWorkerSha256=BASE_SHA, reviewedPeftSource=source_pin())
|
|
59
|
+
return info
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
base.runtime_info = runtime_info
|
|
63
|
+
base.WORKER_VERSION = VERSION
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def artifact(ref):
|
|
67
|
+
fields(ref, ("uri", "sha256", "sizeBytes", "mediaType"))
|
|
68
|
+
require(type(ref["sha256"]) is str and base.SHA.fullmatch(ref["sha256"]) and
|
|
69
|
+
ref["uri"] == "omnius-artifact://sha256/" + ref["sha256"], "Invalid full artifact identity")
|
|
70
|
+
integer(ref["sizeBytes"], 1)
|
|
71
|
+
return ref
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def read_factors(path, maximum):
|
|
75
|
+
"""Exact bounded F32 safetensors parser, with no tensor/framework import."""
|
|
76
|
+
size = path.stat().st_size
|
|
77
|
+
require(8 < size <= maximum, "Adapter safetensors byte limit", "CAPACITY")
|
|
78
|
+
with path.open("rb") as stream:
|
|
79
|
+
data = stream.read(size + 1)
|
|
80
|
+
require(len(data) == size, "Adapter changed during read", "IDENTITY")
|
|
81
|
+
header_size = struct.unpack("<Q", data[:8])[0]
|
|
82
|
+
require(2 <= header_size <= min(4194304, size - 8), "Invalid adapter safetensors header")
|
|
83
|
+
header = base.parse_json(data[8:8 + header_size].decode("utf-8", "strict"))
|
|
84
|
+
require(type(header) is dict and 1 <= len(header) <= 33, "Adapter tensor inventory exceeds bound", "CAPACITY")
|
|
85
|
+
offset, tensors = 0, {}
|
|
86
|
+
for name, value in sorted(header.items(), key=lambda item: item[1].get("data_offsets", [0])[0] if type(item[1]) is dict else -1):
|
|
87
|
+
if name == "__metadata__":
|
|
88
|
+
require(type(value) is dict and all(type(k) is str and type(v) is str for k, v in value.items()), "Invalid safetensors metadata")
|
|
89
|
+
continue
|
|
90
|
+
fields(value, ("dtype", "shape", "data_offsets"))
|
|
91
|
+
require(value["dtype"] == "F32" and type(value["shape"]) is list and len(value["shape"]) == 2,
|
|
92
|
+
"Only matrix F32 LoRA factors are supported", "UNSUPPORTED")
|
|
93
|
+
count = 1
|
|
94
|
+
for dimension in value["shape"]:
|
|
95
|
+
count *= integer(dimension, 1, 1000000)
|
|
96
|
+
require(count * 4 <= maximum, "Adapter tensor byte bound", "CAPACITY")
|
|
97
|
+
bounds = value["data_offsets"]
|
|
98
|
+
require(type(bounds) is list and len(bounds) == 2 and type(bounds[0]) is int and type(bounds[1]) is int and
|
|
99
|
+
bounds[0] == offset and bounds[1] == offset + count * 4 and 8 + header_size + bounds[1] <= size,
|
|
100
|
+
"Overlapping, sparse or out-of-bounds adapter tensor")
|
|
101
|
+
raw = data[8 + header_size + bounds[0]:8 + header_size + bounds[1]]
|
|
102
|
+
require(all(math.isfinite(value[0]) for value in struct.iter_unpack("<f", raw)), "Nonfinite adapter tensor")
|
|
103
|
+
tensors[name] = {"shape": value["shape"], "sha256": base.digest_bytes(raw), "sizeBytes": len(raw)}
|
|
104
|
+
offset = bounds[1]
|
|
105
|
+
require(8 + header_size + offset == size and tensors, "Trailing or missing adapter payload")
|
|
106
|
+
return tensors
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def exact_parent_digests(actual, model):
|
|
110
|
+
"""Complete declared source closure, never a subset or duplicated lineage."""
|
|
111
|
+
parents = model.get("parents")
|
|
112
|
+
require(type(parents) is list and len(parents) <= 128, "Bounded base ancestry required", "IDENTITY")
|
|
113
|
+
expected = [model["modelDigest"]]
|
|
114
|
+
for parent in parents:
|
|
115
|
+
fields(parent, ("modelDigest",), ("revision",))
|
|
116
|
+
require(type(parent["modelDigest"]) is str and base.SHA.fullmatch(parent["modelDigest"]), "Invalid base ancestor", "IDENTITY")
|
|
117
|
+
expected.append(parent["modelDigest"])
|
|
118
|
+
require(len(expected) == len(set(expected)), "Duplicate/self base ancestry", "IDENTITY")
|
|
119
|
+
return (type(actual) is list and len(actual) == len(expected) and
|
|
120
|
+
all(type(value) is str and base.SHA.fullmatch(value) for value in actual) and
|
|
121
|
+
len(actual) == len(set(actual)) and sorted(actual) == sorted(expected))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def verify_adapter(root, supplied, model, working_limit):
|
|
125
|
+
fields(supplied, ("adapterRoot", "adapterModel", "adapterModelJson", "adapterTensorSitesJson", "moduleBindings", "baseModel", "exportReceipt", "limits"))
|
|
126
|
+
limits = supplied["limits"]
|
|
127
|
+
fields(limits, ("maxAdapterBytes", "maxRank", "maxModules", "maxTargetBytes", "maxAdapterMultiplyAdds"))
|
|
128
|
+
integer(limits["maxAdapterBytes"], 1, 67108864)
|
|
129
|
+
integer(limits["maxRank"], 1, 64)
|
|
130
|
+
integer(limits["maxModules"], 1, 16)
|
|
131
|
+
integer(limits["maxTargetBytes"], 1, 1073741824)
|
|
132
|
+
integer(limits["maxAdapterMultiplyAdds"], 1, 100000000000000)
|
|
133
|
+
require(root.is_absolute() and root.is_dir() and not root.is_symlink() and root.resolve() == root,
|
|
134
|
+
"Exact absolute local adapter root required", "IDENTITY")
|
|
135
|
+
manifest = supplied["adapterModel"]
|
|
136
|
+
require(manifest.get("schema") == "omnius.nol.model.v1" and manifest.get("format") == "lora", "LoRA asset manifest required")
|
|
137
|
+
base.verify_identity(supplied["adapterModelJson"], {k: v for k, v in manifest.items() if k not in ("id", "modelDigest")}, manifest["modelDigest"])
|
|
138
|
+
base.verify_identity(supplied["adapterTensorSitesJson"], manifest["tensorSites"], manifest["architectureMapDigest"])
|
|
139
|
+
require(exact_parent_digests([parent["modelDigest"] for parent in manifest["parents"]], model) and
|
|
140
|
+
all(base.same_json(manifest[key], model[key]) for key in ("architecture", "tokenizerDigest", "chatTemplateDigest", "specialTokens", "contextLength")),
|
|
141
|
+
"Adapter exact base-model parent/semantics mismatch", "IDENTITY")
|
|
142
|
+
paths, total = set(), 0
|
|
143
|
+
require(type(manifest["files"]) is list and 2 <= len(manifest["files"]) <= 4, "Bounded complete adapter file inventory required")
|
|
144
|
+
for part in manifest["files"]:
|
|
145
|
+
fields(part, ("path", "role", "artifact"))
|
|
146
|
+
ref = artifact(part["artifact"])
|
|
147
|
+
require(part["path"] not in paths, "Duplicate adapter file")
|
|
148
|
+
paths.add(part["path"])
|
|
149
|
+
total += ref["sizeBytes"]
|
|
150
|
+
require(total <= limits["maxAdapterBytes"], "Aggregate adapter file byte allowance", "CAPACITY")
|
|
151
|
+
require(base.hash_file(base.safe_path(root, part["path"]), limits["maxAdapterBytes"]) ==
|
|
152
|
+
{"sha256": ref["sha256"], "sizeBytes": ref["sizeBytes"]}, "Adapter file identity mismatch", "IDENTITY")
|
|
153
|
+
actual_paths = set()
|
|
154
|
+
for path in root.rglob("*"):
|
|
155
|
+
require(not path.is_symlink(), "Adapter tree contains a symlink", "IDENTITY")
|
|
156
|
+
if path.is_file():
|
|
157
|
+
actual_paths.add(path.relative_to(root).as_posix())
|
|
158
|
+
require(paths == actual_paths and {"adapter_config.json", "adapter_model.safetensors"} <= paths,
|
|
159
|
+
"Undeclared, missing or nonstandard adapter files", "IDENTITY")
|
|
160
|
+
require(total * 6 + 2097152 <= working_limit, "Adapter pre-parse byte/tensor working admission failed", "CAPACITY")
|
|
161
|
+
config = base.parse_json(base.safe_path(root, "adapter_config.json").read_text("utf-8"))
|
|
162
|
+
base_model = supplied["baseModel"]
|
|
163
|
+
fields(base_model, ("nameOrPath", "revision", "taskType"))
|
|
164
|
+
require(type(base_model["nameOrPath"]) is str and 1 <= len(base_model["nameOrPath"]) <= 400 and
|
|
165
|
+
base_model["nameOrPath"] == base_model["nameOrPath"].strip() and
|
|
166
|
+
type(base_model["revision"]) is str and re.fullmatch("[a-f0-9]{40,64}", base_model["revision"]) and
|
|
167
|
+
base_model["taskType"] == "CAUSAL_LM", "Explicit pinned causal-LM upstream base identity required")
|
|
168
|
+
modules = supplied["moduleBindings"]
|
|
169
|
+
require(type(modules) is list and 1 <= len(modules) <= limits["maxModules"], "Module allowance exceeded", "CAPACITY")
|
|
170
|
+
names, sites = set(), set()
|
|
171
|
+
rank = integer(config.get("r"), 1, limits["maxRank"])
|
|
172
|
+
expected = {"peft_type": "LORA", "task_type": "CAUSAL_LM", "base_model_name_or_path": base_model["nameOrPath"],
|
|
173
|
+
"revision": base_model["revision"], "target_modules": "^(?:" + "|".join(re.escape(value["modulePath"]) for value in sorted(modules, key=lambda item: item["modulePath"])) + ")$",
|
|
174
|
+
"r": rank, "lora_alpha": rank, "lora_dropout": 0, "bias": "none", "fan_in_fan_out": False,
|
|
175
|
+
"inference_mode": True, "init_lora_weights": True, "use_rslora": False, "use_dora": False,
|
|
176
|
+
"rank_pattern": {}, "alpha_pattern": {}}
|
|
177
|
+
require(base.same_json(config, expected), "Only exact standard NOL F32 LoRA config is supported", "UNSUPPORTED")
|
|
178
|
+
tensors = read_factors(base.safe_path(root, "adapter_model.safetensors"), limits["maxAdapterBytes"])
|
|
179
|
+
factor_names, target_bytes, factor_bytes = set(), 0, 0
|
|
180
|
+
geometry = []
|
|
181
|
+
for item in modules:
|
|
182
|
+
fields(item, ("siteId", "modulePath", "moduleType", "layout"))
|
|
183
|
+
require(item["moduleType"] == "torch.nn.Linear" and item["layout"] == "out_in" and
|
|
184
|
+
type(item["modulePath"]) is str and re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_0-9]+)*", item["modulePath"]),
|
|
185
|
+
"Only explicitly bound ordinary nn.Linear modules are supported", "UNSUPPORTED")
|
|
186
|
+
require(item["modulePath"] not in names and item["siteId"] not in sites, "Duplicate LoRA module/site")
|
|
187
|
+
names.add(item["modulePath"]); sites.add(item["siteId"])
|
|
188
|
+
site = next((site for site in model["tensorSites"] if site["id"] == item["siteId"]), None)
|
|
189
|
+
require(site is not None and site["kind"] == "parameter" and site["name"] == item["modulePath"] + ".weight" and
|
|
190
|
+
len(site["shape"]) == 2 and site["dtype"] in ("f32", "f16", "bf16"), "Native parameter geometry binding required", "IDENTITY")
|
|
191
|
+
output, input_width = site["shape"]
|
|
192
|
+
for part, shape in (("A", [rank, input_width]), ("B", [output, rank])):
|
|
193
|
+
key = "base_model.model." + item["modulePath"] + ".lora_" + part + ".weight"
|
|
194
|
+
require(key in tensors and tensors[key]["shape"] == shape, "Missing, wrong-shaped or unexpected LoRA factor", "IDENTITY")
|
|
195
|
+
factor_names.add(key); factor_bytes += tensors[key]["sizeBytes"]
|
|
196
|
+
target_bytes += output * input_width * (4 if site["dtype"] == "f32" else 2)
|
|
197
|
+
geometry.append({**item, "parameterName": site["name"], "shape": site["shape"], "dtype": site["dtype"], "rank": rank, "scaling": 1})
|
|
198
|
+
require(set(tensors) == factor_names, "Unexpected LoRA tensor keys", "IDENTITY")
|
|
199
|
+
require(target_bytes <= limits["maxTargetBytes"], "Targeted base hashing byte allowance", "CAPACITY")
|
|
200
|
+
require(total * 2 + factor_bytes * 4 + 2097152 <= working_limit, "Adapter load working byte admission failed", "CAPACITY")
|
|
201
|
+
receipt_ref = artifact(supplied["exportReceipt"])
|
|
202
|
+
receipt_part = next((part for part in manifest["files"] if base.same_json(part["artifact"], receipt_ref)), None)
|
|
203
|
+
require(receipt_part is not None and receipt_ref["mediaType"] == "application/json", "Full export receipt must belong to the adapter manifest", "IDENTITY")
|
|
204
|
+
require(paths == {"adapter_config.json", "adapter_model.safetensors", receipt_part["path"]} and
|
|
205
|
+
receipt_part["path"].endswith(".json"), "Only complete standard adapter assets and their export receipt are supported", "UNSUPPORTED")
|
|
206
|
+
receipt = base.parse_json(base.safe_path(root, receipt_part["path"]).read_text("utf-8"))
|
|
207
|
+
require(receipt.get("schema") == "omnius.nol.lora-export.v1" and receipt.get("parentModelDigest") == model["modelDigest"] and
|
|
208
|
+
exact_parent_digests(receipt.get("parentModelDigests"), model) and
|
|
209
|
+
base.same_json(receipt.get("baseModel"), base_model) and type(receipt.get("recipeDigest")) is str and base.SHA.fullmatch(receipt["recipeDigest"]),
|
|
210
|
+
"Adapter export lineage mismatch", "IDENTITY")
|
|
211
|
+
require(len(manifest["tensorSites"]) == 2 * len(modules) and
|
|
212
|
+
{site["name"] for site in manifest["tensorSites"]} == factor_names and
|
|
213
|
+
all(site["kind"] == "parameter" and site["dtype"] == "f32" and site["shape"] == tensors[site["name"]]["shape"] for site in manifest["tensorSites"]),
|
|
214
|
+
"Adapter manifest factor map mismatch", "IDENTITY")
|
|
215
|
+
return {"manifest": manifest, "config": config, "geometry": geometry, "tensors": tensors, "factorBytes": factor_bytes,
|
|
216
|
+
"targetBytes": target_bytes, "totalBytes": total, "recipeDigest": receipt["recipeDigest"], "exportReceipt": receipt_ref, "limits": limits}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def tensor_sha(tensor, torch):
|
|
220
|
+
require(tensor.is_contiguous(), "Hashing requires an actual contiguous tensor", "IDENTITY")
|
|
221
|
+
raw = tensor.detach().view(torch.uint8).reshape(-1)
|
|
222
|
+
digest = hashlib.sha256()
|
|
223
|
+
# At most one 1MiB CPU chunk plus its bytes copy; never copy a whole 4B model.
|
|
224
|
+
for offset in range(0, raw.numel(), 1048576):
|
|
225
|
+
digest.update(raw[offset:offset + 1048576].cpu().numpy().tobytes())
|
|
226
|
+
return digest.hexdigest()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def storage_identity(parameter):
|
|
230
|
+
return {"object": id(parameter), "data": parameter.data_ptr(), "version": parameter._version,
|
|
231
|
+
"shape": list(parameter.shape), "dtype": str(parameter.dtype), "device": str(parameter.device)}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def attach_peft_model(model, approved, torch, device):
|
|
235
|
+
"""Actual PEFT public loading path, also directly testable with CPU Linear.
|
|
236
|
+
Runtime.load itself always uses the frozen approved CUDA/model gate.
|
|
237
|
+
"""
|
|
238
|
+
from peft import PeftModel
|
|
239
|
+
from peft.tuners.lora.layer import Linear
|
|
240
|
+
originals = dict(model.named_parameters(remove_duplicate=False))
|
|
241
|
+
identities = {name: storage_identity(parameter) for name, parameter in originals.items()}
|
|
242
|
+
target_hashes = {}
|
|
243
|
+
for item in approved["geometry"]:
|
|
244
|
+
module = model.get_submodule(item["modulePath"])
|
|
245
|
+
require(type(module) is torch.nn.Linear and list(module.weight.shape) == item["shape"] and module.weight.device == torch.device(device),
|
|
246
|
+
"Actual target is not the bound native Linear geometry/device", "IDENTITY")
|
|
247
|
+
require(module.weight.dtype == {"f32": torch.float32, "f16": torch.float16, "bf16": torch.bfloat16}[item["dtype"]],
|
|
248
|
+
"Actual target dtype differs from the parent manifest", "IDENTITY")
|
|
249
|
+
target_hashes[item["parameterName"]] = tensor_sha(module.weight, torch)
|
|
250
|
+
root = approved["root"]
|
|
251
|
+
kwargs = {"adapter_name": "default", "is_trainable": False, "autocast_adapter_dtype": True,
|
|
252
|
+
"low_cpu_mem_usage": False, "local_files_only": True, "ignore_mismatched_sizes": False}
|
|
253
|
+
wrapped = PeftModel.from_pretrained(model, str(root), **kwargs)
|
|
254
|
+
# from_pretrained returns only the model. This second bounded public load
|
|
255
|
+
# returns the actual key diagnostics; no monkeypatch or warning suppression.
|
|
256
|
+
diagnostics = wrapped.load_adapter(str(root), **kwargs)
|
|
257
|
+
require(not diagnostics.missing_keys and not diagnostics.unexpected_keys, "PEFT reported missing or unexpected adapter keys", "IDENTITY")
|
|
258
|
+
loaded_config = wrapped.peft_config["default"]
|
|
259
|
+
actual_config = base.parse_json(json.dumps({key: getattr(loaded_config, key) for key in approved["config"]}))
|
|
260
|
+
require(base.same_json(actual_config, approved["config"]),
|
|
261
|
+
"Actual PEFT configuration differs from the full-hashed source", "IDENTITY")
|
|
262
|
+
wrapped.eval()
|
|
263
|
+
for parameter in wrapped.parameters():
|
|
264
|
+
parameter.requires_grad_(False)
|
|
265
|
+
actual = {name: module for name, module in wrapped.named_modules() if isinstance(module, Linear)}
|
|
266
|
+
expected = {"base_model.model." + item["modulePath"] for item in approved["geometry"]}
|
|
267
|
+
require(set(actual) == expected and set(wrapped.peft_config) == {"default"}, "PEFT inserted undeclared adapter modules", "IDENTITY")
|
|
268
|
+
modules, factors = {}, {}
|
|
269
|
+
for item in approved["geometry"]:
|
|
270
|
+
path = "base_model.model." + item["modulePath"]
|
|
271
|
+
module = actual[path]
|
|
272
|
+
require(type(module) is Linear and not module.merged and not module.merged_adapters and
|
|
273
|
+
module.get_base_layer().weight is originals[item["parameterName"]] and
|
|
274
|
+
set(module.lora_A) == set(module.lora_B) == {"default"} and module.scaling == {"default": 1.0} and
|
|
275
|
+
module.r == {"default": item["rank"]} and not module.use_dora.get("default", False),
|
|
276
|
+
"Unexpected PEFT geometry/scaling/merge state", "IDENTITY")
|
|
277
|
+
modules[item["modulePath"]] = module
|
|
278
|
+
for part in ("A", "B"):
|
|
279
|
+
factor = getattr(module, "lora_" + part)["default"].weight
|
|
280
|
+
key = path + ".lora_" + part + ".weight"
|
|
281
|
+
require(factor.dtype == torch.float32 and factor.device == torch.device(device) and
|
|
282
|
+
list(factor.shape) == approved["tensors"][key]["shape"] and tensor_sha(factor, torch) == approved["tensors"][key]["sha256"],
|
|
283
|
+
"Serialized F32 adapter factors changed dtype/bits/device", "IDENTITY")
|
|
284
|
+
factors[key] = factor
|
|
285
|
+
wrapped.base_model.disable_adapter_layers()
|
|
286
|
+
state = {"model": wrapped, "originals": originals, "identities": identities, "targetHashes": target_hashes,
|
|
287
|
+
"modules": modules, "factors": factors, "approved": approved, "device": device}
|
|
288
|
+
verify_state(state, torch, False)
|
|
289
|
+
return state
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def verify_state(state, torch, enabled):
|
|
293
|
+
for name, parameter in state["originals"].items():
|
|
294
|
+
require(storage_identity(parameter) == state["identities"][name], "Original base parameter storage/version identity changed", "RESET")
|
|
295
|
+
for name, expected in state["targetHashes"].items():
|
|
296
|
+
require(tensor_sha(state["originals"][name], torch) == expected, "Targeted original base parameter bytes changed", "RESET")
|
|
297
|
+
for module in state["modules"].values():
|
|
298
|
+
require(not module.merged and not module.merged_adapters and module.disable_adapters is (not enabled) and
|
|
299
|
+
module.active_adapters == ["default"],
|
|
300
|
+
"PEFT merged or enabled-state mismatch", "RESET")
|
|
301
|
+
for name, factor in state["factors"].items():
|
|
302
|
+
require(factor.dtype == torch.float32 and factor.device == torch.device(state["device"]) and
|
|
303
|
+
tensor_sha(factor, torch) == state["approved"]["tensors"][name]["sha256"], "PEFT factor mutation/dtype/device mismatch", "RESET")
|
|
304
|
+
return {"schema": "omnius.nol.peft-state.v1", "adapterModelDigest": state["approved"]["manifest"]["modelDigest"],
|
|
305
|
+
"enabled": enabled, "merged": False, "adapterName": "default", "factorDtype": "f32",
|
|
306
|
+
"factorHashes": {name: state["approved"]["tensors"][name]["sha256"] for name in sorted(state["factors"])},
|
|
307
|
+
"targetedBaseWeightHashes": state["targetHashes"], "baseParameterCount": len(state["originals"]),
|
|
308
|
+
"baseParameterIdentityDigest": base.digest_bytes(base.canonical_simple(state["identities"]).encode()),
|
|
309
|
+
"baseProofScope": "all_original_storage_version_identities_and_targeted_full_weight_bytes",
|
|
310
|
+
"fullBaseMemoryBitwiseHashPerformed": False, "retainedCache": False}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class Runtime(base.Runtime):
|
|
314
|
+
def __init__(self):
|
|
315
|
+
super().__init__()
|
|
316
|
+
self.peft_state = None
|
|
317
|
+
self.poisoned = self.closed = False
|
|
318
|
+
|
|
319
|
+
def ready(self):
|
|
320
|
+
require(not self.closed and not self.poisoned and self.peft_state is not None, "PEFT worker is closed/poisoned/unloaded", "RESET")
|
|
321
|
+
super().ready()
|
|
322
|
+
|
|
323
|
+
def load(self, payload):
|
|
324
|
+
fields(payload, ("checkpointRoot", "artifactRoot", "model", "binding", "gpuUuid", "dtype", "identity", "dependencyLockPath", "limits", "peft"))
|
|
325
|
+
require(not self.closed and not self.poisoned and not self.loaded, "PEFT worker cannot be reloaded", "RESET")
|
|
326
|
+
require(sys.byteorder == "little", "Only explicit little-endian factor hosts are supported", "UNSUPPORTED")
|
|
327
|
+
supplied = payload["peft"]
|
|
328
|
+
root = Path(supplied["adapterRoot"])
|
|
329
|
+
approved = verify_adapter(root, supplied, payload["model"], integer(payload["limits"]["maxWorkingBytes"], 1))
|
|
330
|
+
checkpoint = Path(payload["checkpointRoot"]).resolve(strict=True)
|
|
331
|
+
require(not root.is_relative_to(checkpoint) and not checkpoint.is_relative_to(root), "Adapter/checkpoint roots overlap", "IDENTITY")
|
|
332
|
+
plain = {key: value for key, value in payload.items() if key != "peft"}
|
|
333
|
+
result = super().load(plain)
|
|
334
|
+
try:
|
|
335
|
+
approved["root"] = root
|
|
336
|
+
self.peft_state = attach_peft_model(self.model, approved, self.torch, "cuda:0")
|
|
337
|
+
self.model = self.peft_state["model"]
|
|
338
|
+
# Re-read every immutable source file after PEFT consumption.
|
|
339
|
+
verify_adapter(root, supplied, payload["model"], payload["limits"]["maxWorkingBytes"])
|
|
340
|
+
self.torch.cuda.synchronize()
|
|
341
|
+
result.update(implementation=VERSION, baseWorkerSha256=BASE_SHA,
|
|
342
|
+
supportedRuntimeOperations=[], supportedParameterOperations=[],
|
|
343
|
+
supportedAssets=["standard_peft_unmerged_lora"],
|
|
344
|
+
adapterModelDigest=approved["manifest"]["modelDigest"], sourceRecipeDigest=approved["recipeDigest"],
|
|
345
|
+
peftState=verify_state(self.peft_state, self.torch, False),
|
|
346
|
+
operationRestrictions={"nativeRecipes": "unsupported", "tokenScope": "all_computation_positions",
|
|
347
|
+
"parameterMerge": "prohibited", "adapterStorageDtype": "f32",
|
|
348
|
+
"numericalPolicy": "native_peft_f32_low_rank_branch_plus_base_result_cast_to_base_output_dtype"},
|
|
349
|
+
nativeCapabilityAuthority=False)
|
|
350
|
+
return result
|
|
351
|
+
except BaseException as error:
|
|
352
|
+
base.private_diagnostic(error)
|
|
353
|
+
self.poisoned = True
|
|
354
|
+
raise Rejected("PEFT_LOAD_FAILED", "PEFT load/identity verification failed", True) from error
|
|
355
|
+
|
|
356
|
+
def reset(self):
|
|
357
|
+
try:
|
|
358
|
+
if self.peft_state is not None:
|
|
359
|
+
self.peft_state["model"].base_model.disable_adapter_layers()
|
|
360
|
+
state = verify_state(self.peft_state, self.torch, False)
|
|
361
|
+
else:
|
|
362
|
+
state = None
|
|
363
|
+
result = super().reset()
|
|
364
|
+
if state is not None:
|
|
365
|
+
result["peft"] = state
|
|
366
|
+
self.last_reset = result
|
|
367
|
+
return result
|
|
368
|
+
except BaseException as error:
|
|
369
|
+
self.poisoned = True
|
|
370
|
+
raise Rejected("RESET", "PEFT reset could not verify disabled original state", True) from error
|
|
371
|
+
|
|
372
|
+
def install(self, recipe):
|
|
373
|
+
require(recipe is None, "Native operation recipes cannot mix with serialized PEFT serving", "UNSUPPORTED")
|
|
374
|
+
return []
|
|
375
|
+
|
|
376
|
+
def generate(self, payload):
|
|
377
|
+
self.ready()
|
|
378
|
+
fields(payload, ("messages", "recipe", "recipeIdentityJson", "cacheKeyDigest", "seed", "maxTokens", "decoding", "adapterMode"))
|
|
379
|
+
require(payload["recipe"] is None and payload["recipeIdentityJson"] is None and payload["adapterMode"] in ("disabled", "enabled"),
|
|
380
|
+
"Only explicit disabled/enabled serialized adapter arms are supported", "UNSUPPORTED")
|
|
381
|
+
require(self.last_reset is not None and self.last_reset.get("peft", {}).get("enabled") is False, "Explicit verified disabled reset required", "RESET")
|
|
382
|
+
prompt = self.tokenize({"messages": payload["messages"]})["tokenIds"]
|
|
383
|
+
maximum = integer(payload["maxTokens"], 1, self.limits["maxOutputTokens"])
|
|
384
|
+
positions = sum(len(prompt) + index for index in range(maximum))
|
|
385
|
+
approved = self.peft_state["approved"]
|
|
386
|
+
multiply_adds = sum(positions * item["rank"] * sum(item["shape"]) for item in approved["geometry"])
|
|
387
|
+
working = approved["totalBytes"] * 2 + approved["factorBytes"] * 4 + 2097152 + sum(
|
|
388
|
+
(len(prompt) + maximum) * (item["shape"][1] * 4 + item["rank"] * 8 + item["shape"][0] * 16)
|
|
389
|
+
for item in approved["geometry"])
|
|
390
|
+
require(multiply_adds <= approved["limits"]["maxAdapterMultiplyAdds"] and working <= self.limits["maxWorkingBytes"],
|
|
391
|
+
"Adapter generation arithmetic/working admission failed", "CAPACITY")
|
|
392
|
+
enabled = payload["adapterMode"] == "enabled"
|
|
393
|
+
try:
|
|
394
|
+
verify_state(self.peft_state, self.torch, False)
|
|
395
|
+
if enabled:
|
|
396
|
+
self.model.base_model.enable_adapter_layers()
|
|
397
|
+
for parameter in self.model.parameters(): parameter.requires_grad_(False)
|
|
398
|
+
before = verify_state(self.peft_state, self.torch, True)
|
|
399
|
+
result = super().generate({key: value for key, value in payload.items() if key != "adapterMode"})
|
|
400
|
+
else:
|
|
401
|
+
# Exercise PEFT's documented disabled base path, not a copied
|
|
402
|
+
# model or separately merged checkpoint.
|
|
403
|
+
with self.model.disable_adapter():
|
|
404
|
+
before = verify_state(self.peft_state, self.torch, False)
|
|
405
|
+
result = super().generate({key: value for key, value in payload.items() if key != "adapterMode"})
|
|
406
|
+
after = verify_state(self.peft_state, self.torch, False)
|
|
407
|
+
result["native"]["peft"] = {"adapterMode": payload["adapterMode"], "adapterModelDigest": approved["manifest"]["modelDigest"],
|
|
408
|
+
"sourceRecipeDigest": approved["recipeDigest"], "exportReceipt": approved["exportReceipt"],
|
|
409
|
+
"stateAtForward": before, "stateAfter": after, "parameterMergePerformed": False,
|
|
410
|
+
"adapterMultiplyAddsBound": multiply_adds, "adapterWorkingBytesBound": working}
|
|
411
|
+
return result
|
|
412
|
+
except BaseException:
|
|
413
|
+
try: self.reset()
|
|
414
|
+
except BaseException as error:
|
|
415
|
+
self.poisoned = True
|
|
416
|
+
raise Rejected("RESET", "Failed PEFT trial did not settle to disabled state", True) from error
|
|
417
|
+
raise
|
|
418
|
+
|
|
419
|
+
def profile(self, payload):
|
|
420
|
+
raise Rejected("UNSUPPORTED", "PEFT observation/backward/native operation recipes are not implemented")
|
|
421
|
+
|
|
422
|
+
def close(self):
|
|
423
|
+
if self.closed:
|
|
424
|
+
return {"closed": True, "pid": os.getpid(), "allocationReleaseRequiresHostVerification": True}
|
|
425
|
+
try:
|
|
426
|
+
result = super().close()
|
|
427
|
+
self.peft_state = None
|
|
428
|
+
self.closed = True
|
|
429
|
+
return result
|
|
430
|
+
except BaseException as error:
|
|
431
|
+
self.poisoned = True
|
|
432
|
+
raise Rejected("RESET", "PEFT close failed; process retirement and host settlement required", True) from error
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def serve():
|
|
436
|
+
sys.stdout = sys.stderr
|
|
437
|
+
require(0 < base.MAX_FRAME <= 67108864 and all(base.OWNER.values()), "Private ownership and frame bounds required")
|
|
438
|
+
runtime, sequence = Runtime(), 0
|
|
439
|
+
try:
|
|
440
|
+
while True:
|
|
441
|
+
header = base.read_exact(sys.stdin.buffer, 4)
|
|
442
|
+
if header is None: break
|
|
443
|
+
size = struct.unpack(">I", header)[0]
|
|
444
|
+
require(0 < size <= base.MAX_FRAME, "Frame bound exceeded", "CAPACITY")
|
|
445
|
+
raw = base.read_exact(sys.stdin.buffer, size)
|
|
446
|
+
require(raw is not None, "Truncated request")
|
|
447
|
+
request = base.parse_json(raw.decode("utf-8", "strict"))
|
|
448
|
+
fields(request, ("schema", "kind", "sessionId", "jobId", "ownerId", "generation", "id", "action", "payload"))
|
|
449
|
+
require(request["schema"] == base.PROTOCOL and request["kind"] == "request" and
|
|
450
|
+
all(request[key] == value for key, value in base.OWNER.items()) and request["id"] == sequence + 1,
|
|
451
|
+
"Owner/generation/sequence mismatch", "IDENTITY")
|
|
452
|
+
sequence += 1
|
|
453
|
+
response = {key: request[key] for key in ("schema", "sessionId", "jobId", "ownerId", "generation", "id", "action")}
|
|
454
|
+
response["kind"] = "response"
|
|
455
|
+
closing = False
|
|
456
|
+
try:
|
|
457
|
+
action, payload = request["action"], request["payload"]
|
|
458
|
+
if action == "hello":
|
|
459
|
+
fields(payload, ())
|
|
460
|
+
result = {"protocol": base.PROTOCOL, "workerVersion": VERSION, "workerSha256": base.hash_file(Path(__file__).resolve())["sha256"],
|
|
461
|
+
"baseWorkerSha256": BASE_SHA, "pid": os.getpid(), "loaded": runtime.loaded,
|
|
462
|
+
"torchImported": "torch" in sys.modules, "nativeCapabilityAuthority": False}
|
|
463
|
+
elif action in ("inspect", "load", "tokenize", "generate", "profile"):
|
|
464
|
+
result = getattr(runtime, action)(payload)
|
|
465
|
+
elif action == "confirm_placement": result = runtime.confirm(payload)
|
|
466
|
+
elif action in ("reset", "close"):
|
|
467
|
+
fields(payload, ()); result = getattr(runtime, action)(); closing = action == "close"
|
|
468
|
+
else: raise Rejected("UNSUPPORTED", "Unknown PEFT worker action")
|
|
469
|
+
response["result"] = result
|
|
470
|
+
except Rejected as error:
|
|
471
|
+
closing = error.fatal or action in ("load", "close") or runtime.poisoned
|
|
472
|
+
response["error"] = {"code": error.code, "message": str(error)[:4096], "fatal": closing}
|
|
473
|
+
except BaseException as error:
|
|
474
|
+
base.private_diagnostic(error); closing = True
|
|
475
|
+
response["error"] = {"code": "RUNTIME_FAILURE", "message": type(error).__name__, "fatal": True}
|
|
476
|
+
encoded = json.dumps(response, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
477
|
+
require(len(encoded) <= base.MAX_FRAME, "Response frame bound exceeded", "CAPACITY")
|
|
478
|
+
base.WIRE_OUT.write(struct.pack(">I", len(encoded)) + encoded); base.WIRE_OUT.flush()
|
|
479
|
+
if closing: break
|
|
480
|
+
finally:
|
|
481
|
+
runtime.close()
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
if __name__ == "__main__":
|
|
485
|
+
try: serve()
|
|
486
|
+
except BaseException as error:
|
|
487
|
+
base.private_diagnostic(error)
|
|
488
|
+
sys.exit(1)
|