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,920 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Job-owned NOL compute worker. Stdlib-only until an explicit zero-token load.
|
|
3
|
+
|
|
4
|
+
Transport: uint32 big-endian UTF-8 JSON frames. Stdout is never a log stream.
|
|
5
|
+
The host owns GPU leasing, artifact publication, native receipts and grading.
|
|
6
|
+
This process reports observed facts; it cannot attest broker custody by itself.
|
|
7
|
+
"""
|
|
8
|
+
import contextlib
|
|
9
|
+
import gc
|
|
10
|
+
import hashlib
|
|
11
|
+
import importlib.metadata
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import re
|
|
17
|
+
import struct
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import traceback
|
|
21
|
+
|
|
22
|
+
PROTOCOL = "omnius.nol.worker.v1"
|
|
23
|
+
WORKER_VERSION = "omnius.nol.transformers.v1"
|
|
24
|
+
MAX_FRAME = int(os.environ.get("OMNIUS_NOL_MAX_FRAME_BYTES", "1048576"))
|
|
25
|
+
WIRE_OUT = sys.stdout.buffer
|
|
26
|
+
OWNER = {"sessionId": os.environ.get("OMNIUS_NOL_WORKER_SESSION", ""),
|
|
27
|
+
"jobId": os.environ.get("OMNIUS_NOL_JOB_ID", ""),
|
|
28
|
+
"ownerId": os.environ.get("OMNIUS_NOL_OWNER_ID", ""),
|
|
29
|
+
"generation": int(os.environ.get("OMNIUS_NOL_GENERATION", "0"))}
|
|
30
|
+
UUID = re.compile(r"^GPU-[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
|
31
|
+
SHA = re.compile(r"^[a-f0-9]{64}$")
|
|
32
|
+
RUNTIME_OPS = {"NEURON_ADD", "NEURON_GAIN", "NEURON_REPLACE", "RESIDUAL_ADD", "DIRECTION_PROJECT"}
|
|
33
|
+
PARAMETER_OPS = {"WEIGHT_ADD", "WEIGHT_GAIN", "WEIGHT_REPLACE", "WEIGHT_PROJECT", "LOW_RANK_UPDATE", "WEIGHT_MERGE"}
|
|
34
|
+
NATIVE_CODE = re.compile(r"(?:\.py|\.pyc|\.pyd|\.dll|\.dylib|\.ptx|\.cubin|\.so(?:\.[0-9]+)*)$", re.IGNORECASE)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Rejected(Exception):
|
|
38
|
+
def __init__(self, code, message, fatal=False):
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.code, self.fatal = code, fatal
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def require(condition, message, code="INVALID_REQUEST"):
|
|
44
|
+
if not condition:
|
|
45
|
+
raise Rejected(code, message)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fields(value, required, optional=()):
|
|
49
|
+
require(type(value) is dict and set(required) <= value.keys() and not (value.keys() - set(required) - set(optional)), "Unknown or missing fields")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def integer(value, minimum=0, maximum=9007199254740991):
|
|
53
|
+
require(type(value) is int and minimum <= value <= maximum, "Invalid bounded integer")
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def number(value):
|
|
58
|
+
require(type(value) in (int, float) and math.isfinite(value), "Nonfinite numeric value")
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def private_diagnostic(error):
|
|
63
|
+
sys.stderr.write("".join(traceback.format_exception(type(error), error, error.__traceback__, limit=12))[-8192:] + "\n")
|
|
64
|
+
sys.stderr.flush()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def unique_object(pairs):
|
|
68
|
+
out = {}
|
|
69
|
+
for key, value in pairs:
|
|
70
|
+
require(key not in out, "Duplicate JSON object property")
|
|
71
|
+
out[key] = value
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_json(raw):
|
|
76
|
+
return json.loads(raw, object_pairs_hook=unique_object,
|
|
77
|
+
parse_int=lambda text: -0.0 if text == "-0" else int(text),
|
|
78
|
+
parse_constant=lambda _: (_ for _ in ()).throw(Rejected("INVALID_JSON", "Nonfinite JSON number")))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def canonical_simple(value):
|
|
82
|
+
"""Only used for runtime/file inventories containing strings and integers.
|
|
83
|
+
Scientific records arrive with their exact host-canonical identity bodies.
|
|
84
|
+
"""
|
|
85
|
+
return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def digest_bytes(value):
|
|
89
|
+
return hashlib.sha256(value).hexdigest()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def hash_file(path, maximum=None):
|
|
93
|
+
path = Path(path)
|
|
94
|
+
require(path.is_file() and not path.is_symlink(), "Input must be a regular nonsymlink file")
|
|
95
|
+
before = path.stat()
|
|
96
|
+
require(maximum is None or before.st_size <= maximum, "File byte budget exceeded", "CAPACITY")
|
|
97
|
+
h, size = hashlib.sha256(), 0
|
|
98
|
+
with path.open("rb") as stream:
|
|
99
|
+
opened = os.fstat(stream.fileno())
|
|
100
|
+
require((opened.st_dev, opened.st_ino) == (before.st_dev, before.st_ino), "File identity changed")
|
|
101
|
+
while True:
|
|
102
|
+
block = stream.read(1024 * 1024)
|
|
103
|
+
if not block:
|
|
104
|
+
break
|
|
105
|
+
h.update(block)
|
|
106
|
+
size += len(block)
|
|
107
|
+
after = os.fstat(stream.fileno())
|
|
108
|
+
require((before.st_size, before.st_mtime_ns, before.st_ctime_ns) ==
|
|
109
|
+
(size, after.st_mtime_ns, after.st_ctime_ns), "File changed while hashing")
|
|
110
|
+
return {"sha256": h.hexdigest(), "sizeBytes": size}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def safe_path(root, relative):
|
|
114
|
+
require(type(relative) is str and relative and not relative.startswith("/") and "\\" not in relative and "\0" not in relative,
|
|
115
|
+
"Invalid relative file path")
|
|
116
|
+
require(all(part not in ("", ".", "..") for part in relative.split("/")), "Invalid relative path component")
|
|
117
|
+
root = Path(root).resolve(strict=True)
|
|
118
|
+
current = root
|
|
119
|
+
for part in relative.split("/"):
|
|
120
|
+
current = current / part
|
|
121
|
+
require(not current.is_symlink(), "Symlinks are not accepted in frozen input paths")
|
|
122
|
+
require(current.resolve(strict=True).is_relative_to(root), "Input escaped its frozen root")
|
|
123
|
+
return current
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def same_json(left, right):
|
|
127
|
+
if type(left) in (int, float) and type(right) in (int, float):
|
|
128
|
+
return left == right and (left != 0 or math.copysign(1, left) == math.copysign(1, right))
|
|
129
|
+
if type(left) is not type(right):
|
|
130
|
+
return False
|
|
131
|
+
if type(left) is dict:
|
|
132
|
+
return left.keys() == right.keys() and all(same_json(left[key], right[key]) for key in left)
|
|
133
|
+
if type(left) is list:
|
|
134
|
+
return len(left) == len(right) and all(same_json(a, b) for a, b in zip(left, right))
|
|
135
|
+
return left == right
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def verify_identity(raw, expected, expected_hash):
|
|
139
|
+
require(type(raw) is str and SHA.fullmatch(expected_hash or ""), "Missing exact identity body")
|
|
140
|
+
require(digest_bytes(raw.encode("utf-8")) == expected_hash and same_json(parse_json(raw), expected), "Frozen identity digest/body mismatch", "IDENTITY")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def verify_model(root, model, identity):
|
|
144
|
+
require(model.get("schema") == "omnius.nol.model.v1", "Unsupported model manifest")
|
|
145
|
+
require(model.get("format") in ("hf", "safetensors", "pytorch"), "Unsupported checkpoint format", "UNSUPPORTED")
|
|
146
|
+
body = {key: value for key, value in model.items() if key not in ("id", "modelDigest")}
|
|
147
|
+
verify_identity(identity["modelJson"], body, model["modelDigest"])
|
|
148
|
+
verify_identity(identity["tensorSitesJson"], model["tensorSites"], model["architectureMapDigest"])
|
|
149
|
+
tokenizer_files, paths = [], set()
|
|
150
|
+
for part in model["files"]:
|
|
151
|
+
fields(part, ("path", "role", "artifact"))
|
|
152
|
+
require(part["path"] not in paths, "Duplicate checkpoint file")
|
|
153
|
+
paths.add(part["path"])
|
|
154
|
+
actual = hash_file(safe_path(root, part["path"]))
|
|
155
|
+
require(actual["sha256"] == part["artifact"]["sha256"] and actual["sizeBytes"] == part["artifact"]["sizeBytes"], "Checkpoint file digest mismatch", "IDENTITY")
|
|
156
|
+
if part["role"] == "tokenizer":
|
|
157
|
+
tokenizer_files.append({"path": part["path"], **actual})
|
|
158
|
+
require("config.json" in paths and any(part["role"] == "weights" for part in model["files"]), "Checkpoint lacks configuration or weights")
|
|
159
|
+
verify_identity(identity["tokenizerJson"], tokenizer_files, model["tokenizerDigest"])
|
|
160
|
+
# A loader must not read undeclared config/tokenizer/shard files, including
|
|
161
|
+
# malicious local code or index files referencing an external checkpoint.
|
|
162
|
+
actual_paths = set()
|
|
163
|
+
for path in Path(root).rglob("*"):
|
|
164
|
+
require(not path.is_symlink(), "Checkpoint contains a symlink")
|
|
165
|
+
if path.is_file():
|
|
166
|
+
actual_paths.add(path.relative_to(Path(root)).as_posix())
|
|
167
|
+
require(actual_paths == paths, "Checkpoint has undeclared or missing files", "IDENTITY")
|
|
168
|
+
config = parse_json(safe_path(root, "config.json").read_text("utf-8"))
|
|
169
|
+
text = config.get("text_config", {})
|
|
170
|
+
require(config.get("model_type") == "qwen3_5" and config.get("architectures") == ["Qwen3_5ForConditionalGeneration"] and
|
|
171
|
+
text.get("num_hidden_layers") == 32 and text.get("hidden_size") == 2560 and text.get("intermediate_size") == 9216 and
|
|
172
|
+
text.get("vocab_size") == 248320 and text.get("hidden_act") == "silu" and not text.get("num_experts") and
|
|
173
|
+
"quantization_config" not in config and model["quantization"]["method"] == "none",
|
|
174
|
+
"Only the approved dense Qwen3.5-4B layout is supported", "UNSUPPORTED")
|
|
175
|
+
for index_name in ("model.safetensors.index.json", "pytorch_model.bin.index.json"):
|
|
176
|
+
if index_name in paths:
|
|
177
|
+
index = parse_json(safe_path(root, index_name).read_text("utf-8"))
|
|
178
|
+
require(set(index["weight_map"].values()) <= paths, "Shard index references an undeclared file", "IDENTITY")
|
|
179
|
+
require(model["architecture"]["layers"] == 32 and model["architecture"]["hiddenSize"] == 2560, "Manifest architecture differs from checkpoint")
|
|
180
|
+
return config
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def runtime_info(lock_path=None, hash_runtime=False, max_bytes=34359738368):
|
|
184
|
+
packages, code = {}, []
|
|
185
|
+
spent = 0
|
|
186
|
+
for distribution in sorted(importlib.metadata.distributions(), key=lambda item: item.metadata.get("Name", "").lower()):
|
|
187
|
+
name = distribution.metadata.get("Name", "")
|
|
188
|
+
if not name:
|
|
189
|
+
continue
|
|
190
|
+
packages[name] = distribution.version
|
|
191
|
+
if hash_runtime:
|
|
192
|
+
entries = []
|
|
193
|
+
for relative in sorted(distribution.files or [], key=str):
|
|
194
|
+
if not NATIVE_CODE.search(str(relative)):
|
|
195
|
+
continue
|
|
196
|
+
path = Path(distribution.locate_file(relative))
|
|
197
|
+
# Symlinked libraries are rejected rather than silently hashing
|
|
198
|
+
# a different native installation than the isolated runtime.
|
|
199
|
+
actual = hash_file(path, max_bytes - spent)
|
|
200
|
+
spent += actual["sizeBytes"]
|
|
201
|
+
entries.append({"path": str(relative), **actual})
|
|
202
|
+
code.append({"name": name, "digest": digest_bytes(canonical_simple(entries).encode()), "files": len(entries)})
|
|
203
|
+
info = {"schema": "omnius.nol.transformers-build.v1", "workerVersion": WORKER_VERSION,
|
|
204
|
+
"workerSha256": hash_file(Path(__file__).resolve())["sha256"], "pythonVersion": sys.version.split()[0],
|
|
205
|
+
"packages": packages, "packageCode": code,
|
|
206
|
+
"pythonExecutableSha256": hash_file(Path(sys.executable).resolve())["sha256"]}
|
|
207
|
+
if lock_path:
|
|
208
|
+
info["dependencyLockDigest"] = hash_file(lock_path, 1048576)["sha256"]
|
|
209
|
+
return info
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def inspect_checkpoint(root):
|
|
213
|
+
"""Safe header inspection only. Never imports a tensor/model framework."""
|
|
214
|
+
root = Path(root).resolve(strict=True)
|
|
215
|
+
config_path = safe_path(root, "config.json")
|
|
216
|
+
require(config_path.stat().st_size <= 1048576, "Configuration byte budget exceeded", "CAPACITY")
|
|
217
|
+
config = parse_json(config_path.read_text("utf-8"))
|
|
218
|
+
tensors, shard_names, total_header = {}, set(), 0
|
|
219
|
+
dtype_bytes = {"F64": 8, "F32": 4, "F16": 2, "BF16": 2, "I64": 8, "I32": 4, "I16": 2, "I8": 1, "U8": 1, "BOOL": 1}
|
|
220
|
+
dtype_names = {"F64": "f64", "F32": "f32", "F16": "f16", "BF16": "bf16", "I64": "i64", "I32": "i32", "I16": "i16", "I8": "i8", "U8": "u8", "BOOL": "bool"}
|
|
221
|
+
for path in sorted(root.rglob("*.safetensors")):
|
|
222
|
+
relative = path.relative_to(root).as_posix()
|
|
223
|
+
path = safe_path(root, relative)
|
|
224
|
+
shard_names.add(relative)
|
|
225
|
+
size = path.stat().st_size
|
|
226
|
+
with path.open("rb") as stream:
|
|
227
|
+
prefix = stream.read(8)
|
|
228
|
+
require(len(prefix) == 8, "Truncated safetensors length")
|
|
229
|
+
length = struct.unpack("<Q", prefix)[0]
|
|
230
|
+
total_header += length
|
|
231
|
+
require(2 <= length <= 16777216 and total_header <= 33554432 and 8 + length <= size,
|
|
232
|
+
"Safetensors header byte budget or boundary exceeded", "CAPACITY")
|
|
233
|
+
header = parse_json(stream.read(length).decode("utf-8", "strict"))
|
|
234
|
+
require(type(header) is dict, "Safetensors header must be an object")
|
|
235
|
+
spans = []
|
|
236
|
+
for name, tensor in header.items():
|
|
237
|
+
if name == "__metadata__":
|
|
238
|
+
require(type(tensor) is dict and all(type(value) is str for value in tensor.values()), "Invalid safetensors metadata")
|
|
239
|
+
continue
|
|
240
|
+
require(name not in tensors and type(name) is str and len(name) <= 4096, "Duplicate or invalid checkpoint parameter")
|
|
241
|
+
fields(tensor, ("dtype", "shape", "data_offsets"))
|
|
242
|
+
dtype, shape, offsets = tensor["dtype"], tensor["shape"], tensor["data_offsets"]
|
|
243
|
+
require(dtype in dtype_bytes and type(shape) is list and len(shape) <= 8, "Unsupported tensor header dtype/shape", "UNSUPPORTED")
|
|
244
|
+
count = 1
|
|
245
|
+
for dimension in shape:
|
|
246
|
+
count *= integer(dimension, 1)
|
|
247
|
+
require(count <= 9007199254740991, "Unsafe tensor element count")
|
|
248
|
+
require(type(offsets) is list and len(offsets) == 2, "Invalid tensor data offsets")
|
|
249
|
+
begin, end = (integer(offset) for offset in offsets)
|
|
250
|
+
require(begin <= end <= size - 8 - length and end - begin == count * dtype_bytes[dtype], "Tensor offsets or element bytes are out of bounds")
|
|
251
|
+
spans.append((begin, end))
|
|
252
|
+
role = "bias" if name.endswith((".bias", "_bias")) else "embedding" if "embed_tokens" in name else "ffn" if ".mlp." in name else "attention" if "attn" in name else "norm" if "norm" in name else "router" if "router" in name else "other"
|
|
253
|
+
item = {"id": "parameter:" + digest_bytes(name.encode())[:24], "kind": "parameter", "name": name,
|
|
254
|
+
"shape": shape, "dtype": dtype_names[dtype], "role": role}
|
|
255
|
+
layer = re.search(r"(?:^|\.)language_model\.layers\.([0-9]+)\.", name)
|
|
256
|
+
if layer:
|
|
257
|
+
item["layer"] = int(layer.group(1))
|
|
258
|
+
tensors[name] = {"site": item, "shard": relative}
|
|
259
|
+
previous = 0
|
|
260
|
+
for begin, end in sorted(spans):
|
|
261
|
+
require(begin == previous, "Safetensors data has overlapping or unclaimed ranges")
|
|
262
|
+
previous = end
|
|
263
|
+
require(previous == size - 8 - length, "Safetensors data has an unclaimed tail")
|
|
264
|
+
index_path = root / "model.safetensors.index.json"
|
|
265
|
+
if index_path.exists():
|
|
266
|
+
require(index_path.stat().st_size <= 16777216 and not index_path.is_symlink(), "Invalid safetensors index")
|
|
267
|
+
index = parse_json(index_path.read_text("utf-8"))
|
|
268
|
+
require(type(index.get("weight_map")) is dict and index["weight_map"].keys() == tensors.keys(), "Shard index omits or invents tensors")
|
|
269
|
+
require(all(type(name) is str and name in shard_names and tensors[key]["shard"] == name for key, name in index["weight_map"].items()), "Shard index references missing or inconsistent files")
|
|
270
|
+
elif len(shard_names) > 1:
|
|
271
|
+
raise Rejected("IDENTITY", "A sharded safetensors checkpoint requires its exact index")
|
|
272
|
+
text = config.get("text_config", {})
|
|
273
|
+
approved = config.get("model_type") == "qwen3_5" and text.get("num_hidden_layers") == 32 and text.get("hidden_size") == 2560 and text.get("intermediate_size") == 9216
|
|
274
|
+
sites = [item["site"] for _, item in sorted(tensors.items())]
|
|
275
|
+
if approved:
|
|
276
|
+
for layer in range(32):
|
|
277
|
+
sites.extend([{"id": f"mlp:{layer}", "kind": "mlp_intermediate", "layer": layer, "width": 9216},
|
|
278
|
+
{"id": f"residual:{layer}", "kind": "residual", "layer": layer, "width": 2560}])
|
|
279
|
+
require(len(sites) <= 100000, "Tensor site inventory exceeds its bound", "CAPACITY")
|
|
280
|
+
return {"config": config, "parameters": [item["site"] for _, item in sorted(tensors.items())], "tensorSites": sites,
|
|
281
|
+
"parameterInventory": "safetensors_headers" if shard_names else "unavailable_no_safe_header",
|
|
282
|
+
"approvedDenseQwen35": approved}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def placement(uuid):
|
|
286
|
+
rows = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,gpu_uuid,used_memory", "--format=csv,noheader,nounits"],
|
|
287
|
+
check=True, capture_output=True, timeout=10, text=True)
|
|
288
|
+
require(len(rows.stdout.encode()) <= 1048576, "Placement inventory exceeds its byte bound")
|
|
289
|
+
resident = [row.split(",") for row in rows.stdout.splitlines() if row.split(",")[0].strip() == str(os.getpid())]
|
|
290
|
+
require(resident and all(row[1].strip() == uuid and float(row[2].strip()) > 0 for row in resident), "Actual CUDA residency differs from the reserved UUID", "PLACEMENT")
|
|
291
|
+
stat = Path(f"/proc/{os.getpid()}/stat").read_text()
|
|
292
|
+
return {"pid": os.getpid(), "gpuUuid": uuid, "startIdentity": stat[stat.rfind(")") + 2:].split()[19]}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class Runtime:
|
|
296
|
+
def __init__(self):
|
|
297
|
+
self.model = self.tokenizer = self.torch = None
|
|
298
|
+
self.loaded = self.confirmed = False
|
|
299
|
+
self.hooks, self.backups, self.edited = [], {}, {}
|
|
300
|
+
self.binding = self.manifest = self.limits = None
|
|
301
|
+
self.artifact_root = self.gpu_uuid = None
|
|
302
|
+
self.sequence_length = self.prompt_length = 0
|
|
303
|
+
self.cache_key = None
|
|
304
|
+
self.reset_epoch = 0
|
|
305
|
+
self.working_bytes = self.arithmetic = 0
|
|
306
|
+
self.last_reset = None
|
|
307
|
+
|
|
308
|
+
def inspect(self, payload):
|
|
309
|
+
fields(payload, (), ("dependencyLockPath", "hashRuntime", "maxRuntimeBytes", "checkpointRoot"))
|
|
310
|
+
build = runtime_info(payload.get("dependencyLockPath"), payload.get("hashRuntime") is True,
|
|
311
|
+
integer(payload.get("maxRuntimeBytes", 34359738368), 1))
|
|
312
|
+
result = {"runtimeBuild": build, "runtimeBuildDigest": digest_bytes(canonical_simple(build).encode())}
|
|
313
|
+
if "checkpointRoot" in payload:
|
|
314
|
+
result["checkpoint"] = inspect_checkpoint(payload["checkpointRoot"])
|
|
315
|
+
return result
|
|
316
|
+
|
|
317
|
+
def load(self, payload):
|
|
318
|
+
fields(payload, ("checkpointRoot", "artifactRoot", "model", "binding", "gpuUuid", "dtype", "identity", "dependencyLockPath", "limits"))
|
|
319
|
+
require(not self.loaded, "Worker is already loaded")
|
|
320
|
+
uuid = payload["gpuUuid"]
|
|
321
|
+
require(type(uuid) is str and UUID.fullmatch(uuid) and os.environ.get("CUDA_VISIBLE_DEVICES") == uuid,
|
|
322
|
+
"Explicit exact single-GPU CUDA scope is required", "PLACEMENT")
|
|
323
|
+
fields(payload["limits"], ("maxInputTokens", "maxOutputTokens", "maxTensorBytes", "maxWorkingBytes", "maxMultiplyAdds"))
|
|
324
|
+
limits = {key: integer(value, 1) for key, value in payload["limits"].items()}
|
|
325
|
+
identity = payload["identity"]
|
|
326
|
+
fields(identity, ("modelJson", "tensorSitesJson", "tokenizerJson", "runtimeBuildJson"))
|
|
327
|
+
root = Path(payload["checkpointRoot"]).resolve(strict=True)
|
|
328
|
+
verify_model(root, payload["model"], identity)
|
|
329
|
+
build = runtime_info(payload["dependencyLockPath"], True)
|
|
330
|
+
verify_identity(identity["runtimeBuildJson"], build, payload["binding"]["runtimeBuildDigest"])
|
|
331
|
+
require(build["dependencyLockDigest"] == payload["binding"]["dependencyLockDigest"], "Dependency lock mismatch", "IDENTITY")
|
|
332
|
+
binding, manifest = payload["binding"], payload["model"]
|
|
333
|
+
require(binding["schema"] == "omnius.nol.runtime.v1" and binding["backend"] == "transformers" and
|
|
334
|
+
all(binding[key] == manifest[key] for key in ("modelDigest", "architectureMapDigest", "tokenizerDigest", "chatTemplateDigest")),
|
|
335
|
+
"Runtime/model binding mismatch", "IDENTITY")
|
|
336
|
+
require(limits["maxInputTokens"] + limits["maxOutputTokens"] <= binding["contextLimit"] <= manifest["contextLength"], "Context budget mismatch", "CAPACITY")
|
|
337
|
+
require(payload["dtype"] in ("float32", "float16", "bfloat16"), "Unsupported compute dtype", "UNSUPPORTED")
|
|
338
|
+
# No import, initialization or model load happens above this boundary.
|
|
339
|
+
os.environ["HF_HUB_OFFLINE"] = "1"
|
|
340
|
+
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
|
341
|
+
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
|
342
|
+
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
|
|
343
|
+
import torch
|
|
344
|
+
from transformers import AutoTokenizer, Qwen3_5ForConditionalGeneration
|
|
345
|
+
require(torch.cuda.is_available() and torch.cuda.device_count() == 1, "CUDA scope is unavailable; CPU fallback is prohibited", "PLACEMENT")
|
|
346
|
+
capability = torch.cuda.get_device_capability(0)
|
|
347
|
+
require(capability >= ((8, 0) if payload["dtype"] == "bfloat16" else (7, 0)), "GPU capability is below the selected runtime minimum", "PLACEMENT")
|
|
348
|
+
torch.use_deterministic_algorithms(True)
|
|
349
|
+
self.torch, self.limits, self.binding, self.manifest = torch, limits, binding, manifest
|
|
350
|
+
self.gpu_uuid, self.artifact_root = uuid, Path(payload["artifactRoot"]).resolve(strict=True)
|
|
351
|
+
try:
|
|
352
|
+
self.tokenizer = AutoTokenizer.from_pretrained(str(root), local_files_only=True, trust_remote_code=False)
|
|
353
|
+
template = self.tokenizer.get_chat_template()
|
|
354
|
+
require(digest_bytes(template.encode()) == manifest["chatTemplateDigest"], "Effective chat template differs from frozen identity", "IDENTITY")
|
|
355
|
+
for name, token_id in manifest["specialTokens"].items():
|
|
356
|
+
actual = getattr(self.tokenizer, name + "_token_id", None) if name in ("bos", "eos", "pad", "unk", "sep", "cls", "mask") else self.tokenizer.get_vocab().get(name)
|
|
357
|
+
require(actual == token_id, "Special-token mapping differs from frozen identity", "IDENTITY")
|
|
358
|
+
self.model = Qwen3_5ForConditionalGeneration.from_pretrained(str(root), local_files_only=True, trust_remote_code=False,
|
|
359
|
+
weights_only=True, dtype=getattr(torch, payload["dtype"]), device_map={"": "cuda:0"}, attn_implementation="eager").eval()
|
|
360
|
+
require(all(parameter.device.type == "cuda" and parameter.device.index == 0 for parameter in self.model.parameters()),
|
|
361
|
+
"Loaded parameters escaped the exact CUDA device", "PLACEMENT")
|
|
362
|
+
self.layers = self.model.model.language_model.layers
|
|
363
|
+
self.parameters = dict(self.model.named_parameters(remove_duplicate=False))
|
|
364
|
+
self.sites = {}
|
|
365
|
+
for site in manifest["tensorSites"]:
|
|
366
|
+
require(site["id"] not in self.sites, "Duplicate tensor-site identity")
|
|
367
|
+
if site["kind"] == "mlp_intermediate":
|
|
368
|
+
layer = self.layers[integer(site["layer"], 0, len(self.layers) - 1)]
|
|
369
|
+
require(type(layer.mlp).__name__ == "Qwen3_5MLP" and layer.mlp.down_proj.in_features == site["width"], "Unsupported MLP hook layout", "UNSUPPORTED")
|
|
370
|
+
elif site["kind"] == "residual":
|
|
371
|
+
layer = self.layers[integer(site["layer"], 0, len(self.layers) - 1)]
|
|
372
|
+
require(type(layer).__name__ == "Qwen3_5DecoderLayer" and layer.hidden_size == site["width"], "Unsupported residual hook layout", "UNSUPPORTED")
|
|
373
|
+
elif site["kind"] == "parameter":
|
|
374
|
+
parameter = self.parameters.get(site["name"])
|
|
375
|
+
dtype_name = str(parameter.dtype).removeprefix("torch.") if parameter is not None else ""
|
|
376
|
+
alias = {"float32": "f32", "float64": "f64", "float16": "f16", "bfloat16": "bf16"}.get(dtype_name)
|
|
377
|
+
require(parameter is not None and list(parameter.shape) == site["shape"] and alias == site["dtype"], "Parameter site shape/dtype mismatch", "IDENTITY")
|
|
378
|
+
else:
|
|
379
|
+
continue # No capability is issued for this site kind.
|
|
380
|
+
self.sites[site["id"]] = site
|
|
381
|
+
torch.cuda.synchronize()
|
|
382
|
+
observed = placement(uuid)
|
|
383
|
+
self.loaded = True
|
|
384
|
+
self.reset_epoch = 1
|
|
385
|
+
return {"binding": binding, "placement": observed, "confirmed": False,
|
|
386
|
+
"implementation": WORKER_VERSION, "supportedRuntimeOperations": sorted(RUNTIME_OPS),
|
|
387
|
+
"supportedParameterOperations": sorted(PARAMETER_OPS - {"WEIGHT_MERGE"}), "siteIds": sorted(self.sites),
|
|
388
|
+
"operationRestrictions": {"units": "raw_only", "neuronReplacement": "scalar_only", "weightMerge": "unsupported_source_reader", "mixedRuntimeParameterRecipes": "unsupported"},
|
|
389
|
+
"usesCache": False, "tokenScopeBasis": "edited_computation_positions",
|
|
390
|
+
"firstGeneratedTokenUsesPromptComputation": True}
|
|
391
|
+
except BaseException as error:
|
|
392
|
+
private_diagnostic(error)
|
|
393
|
+
self.close()
|
|
394
|
+
raise Rejected("LOAD_FAILED", type(error).__name__, True) from error
|
|
395
|
+
|
|
396
|
+
def confirm(self, payload):
|
|
397
|
+
fields(payload, ("pid", "gpuUuid", "startIdentity"))
|
|
398
|
+
require(self.loaded and same_json(payload, placement(self.gpu_uuid)), "Host placement confirmation does not match the actual resident worker", "PLACEMENT")
|
|
399
|
+
self.confirmed = True
|
|
400
|
+
return {"confirmed": True, "binding": self.binding, "placement": payload}
|
|
401
|
+
|
|
402
|
+
def ready(self):
|
|
403
|
+
require(self.loaded and self.confirmed, "Model requires actual host-confirmed CUDA placement", "PLACEMENT")
|
|
404
|
+
|
|
405
|
+
def tokenize(self, payload):
|
|
406
|
+
self.ready()
|
|
407
|
+
fields(payload, ("messages",))
|
|
408
|
+
messages = payload["messages"]
|
|
409
|
+
require(type(messages) is list and 0 < len(messages) <= 1000, "Invalid message inventory")
|
|
410
|
+
for message in messages:
|
|
411
|
+
fields(message, ("role", "content"))
|
|
412
|
+
require(message["role"] in ("system", "user", "assistant") and type(message["content"]) is str, "Only plain text messages are supported", "UNSUPPORTED")
|
|
413
|
+
ids = self.tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,
|
|
414
|
+
enable_thinking=False, return_dict=False, return_tensors=None)
|
|
415
|
+
require(type(ids) is list and all(type(token) is int and 0 <= token < 248320 for token in ids),
|
|
416
|
+
"Tokenizer must return a flat integer token sequence", "IDENTITY")
|
|
417
|
+
require(0 < len(ids) <= self.limits["maxInputTokens"], "Prompt exceeds the frozen native token budget", "CAPACITY")
|
|
418
|
+
return {"tokenIds": ids, "promptTokens": len(ids), "chatTemplateDigest": self.binding["chatTemplateDigest"]}
|
|
419
|
+
|
|
420
|
+
def charge(self, amount):
|
|
421
|
+
self.arithmetic += integer(amount)
|
|
422
|
+
require(self.arithmetic <= self.limits["maxMultiplyAdds"], "Arithmetic budget exceeded", "CAPACITY")
|
|
423
|
+
|
|
424
|
+
def tensor(self, ref):
|
|
425
|
+
fields(ref, ("artifact", "shape", "dtype"))
|
|
426
|
+
artifact = ref["artifact"]
|
|
427
|
+
fields(artifact, ("uri", "sha256", "sizeBytes", "mediaType"))
|
|
428
|
+
require(SHA.fullmatch(artifact["sha256"]) and artifact["uri"] == "omnius-artifact://sha256/" + artifact["sha256"], "Invalid tensor artifact identity")
|
|
429
|
+
require(artifact["mediaType"] == "application/json", "Only bounded NOL JSON tensor operands are supported", "UNSUPPORTED")
|
|
430
|
+
require(artifact["sizeBytes"] <= self.limits["maxTensorBytes"], "Tensor artifact budget exceeded", "CAPACITY")
|
|
431
|
+
path = safe_path(self.artifact_root, artifact["sha256"][:2] + "/" + artifact["sha256"])
|
|
432
|
+
require(hash_file(path, self.limits["maxTensorBytes"]) == {"sha256": artifact["sha256"], "sizeBytes": artifact["sizeBytes"]}, "Tensor operand bytes changed", "IDENTITY")
|
|
433
|
+
data = parse_json(path.read_text("utf-8"))
|
|
434
|
+
fields(data, ("schema", "shape", "dtype", "data"))
|
|
435
|
+
require(data["schema"] == "omnius.nol.tensor.v1" and data["shape"] == ref["shape"] and data["dtype"] == ref["dtype"], "Tensor metadata mismatch", "IDENTITY")
|
|
436
|
+
count = 1
|
|
437
|
+
for dimension in data["shape"]:
|
|
438
|
+
count *= integer(dimension, 1)
|
|
439
|
+
require(type(data["data"]) is list and len(data["data"]) == count, "Tensor element count mismatch")
|
|
440
|
+
for value in data["data"]:
|
|
441
|
+
number(value)
|
|
442
|
+
dtype = {"f32": self.torch.float32, "f64": self.torch.float64, "f16": self.torch.float16, "bf16": self.torch.bfloat16}.get(data["dtype"])
|
|
443
|
+
require(dtype is not None, "Unsupported tensor operand dtype", "UNSUPPORTED")
|
|
444
|
+
self.working_bytes += count * 16
|
|
445
|
+
require(self.working_bytes <= self.limits["maxWorkingBytes"], "Tensor working budget exceeded", "CAPACITY")
|
|
446
|
+
value = self.torch.tensor(data["data"], device="cuda:0", dtype=dtype).reshape(data["shape"])
|
|
447
|
+
require(bool(self.torch.isfinite(value).all()), "Tensor data is not finite in its declared dtype")
|
|
448
|
+
return value.to(self.torch.float64)
|
|
449
|
+
|
|
450
|
+
def positions(self, scope):
|
|
451
|
+
fields(scope, ("kind",), ("positions",))
|
|
452
|
+
kind = scope["kind"]
|
|
453
|
+
require(kind in ("all", "prompt", "generated", "positions"), "Unknown computation token scope", "UNSUPPORTED")
|
|
454
|
+
if kind == "all":
|
|
455
|
+
return list(range(self.sequence_length))
|
|
456
|
+
if kind == "prompt":
|
|
457
|
+
return list(range(min(self.prompt_length, self.sequence_length)))
|
|
458
|
+
if kind == "generated":
|
|
459
|
+
return list(range(self.prompt_length, self.sequence_length))
|
|
460
|
+
values = scope.get("positions")
|
|
461
|
+
require(type(values) is list and len(values) == len(set(values)), "Invalid computation position mask")
|
|
462
|
+
for value in values:
|
|
463
|
+
integer(value)
|
|
464
|
+
return [value for value in values if value < self.sequence_length]
|
|
465
|
+
|
|
466
|
+
def reset(self):
|
|
467
|
+
if not self.loaded:
|
|
468
|
+
return {"loaded": False, "hooks": 0, "restoredParameters": [], "retainedCache": False}
|
|
469
|
+
for handle in self.hooks:
|
|
470
|
+
handle.remove()
|
|
471
|
+
self.hooks = []
|
|
472
|
+
restored = []
|
|
473
|
+
with self.torch.no_grad():
|
|
474
|
+
for name, backup in self.backups.items():
|
|
475
|
+
parameter = self.parameters[name]
|
|
476
|
+
parameter.copy_(backup)
|
|
477
|
+
require(self.torch.equal(parameter.contiguous().view(self.torch.uint8), backup.contiguous().view(self.torch.uint8)), "Parameter restoration failed", "RESET")
|
|
478
|
+
restored.append(name)
|
|
479
|
+
self.backups.clear()
|
|
480
|
+
self.edited = {}
|
|
481
|
+
self.cache_key = None
|
|
482
|
+
self.sequence_length = self.prompt_length = 0
|
|
483
|
+
self.working_bytes = self.arithmetic = 0
|
|
484
|
+
self.torch.cuda.synchronize()
|
|
485
|
+
self.torch.cuda.empty_cache()
|
|
486
|
+
self.reset_epoch += 1
|
|
487
|
+
self.last_reset = {"loaded": True, "binding": self.binding, "epoch": self.reset_epoch, "hooks": 0,
|
|
488
|
+
"restoredParameters": restored, "retainedCache": False, "placement": placement(self.gpu_uuid)}
|
|
489
|
+
return self.last_reset
|
|
490
|
+
|
|
491
|
+
def basis(self, ref, dimension):
|
|
492
|
+
basis = self.tensor(ref)
|
|
493
|
+
if basis.ndim == 1:
|
|
494
|
+
basis = basis.unsqueeze(0)
|
|
495
|
+
require(basis.ndim == 2 and basis.shape[1] == dimension and basis.shape[0] <= dimension,
|
|
496
|
+
"Projection basis dimensions differ from canonical row basis")
|
|
497
|
+
self.charge((2 * dimension + 1) * basis.shape[0] ** 2)
|
|
498
|
+
gram = basis @ basis.T
|
|
499
|
+
require(self.torch.allclose(gram, self.torch.eye(basis.shape[0], dtype=basis.dtype, device=basis.device), atol=1e-8, rtol=0), "Projection basis is not orthonormal")
|
|
500
|
+
return basis
|
|
501
|
+
|
|
502
|
+
def parameter_edit(self, op, site):
|
|
503
|
+
parameter = self.parameters[site["name"]]
|
|
504
|
+
if site["name"] not in self.backups:
|
|
505
|
+
self.working_bytes += parameter.numel() * parameter.element_size()
|
|
506
|
+
require(self.working_bytes <= self.limits["maxWorkingBytes"], "Parameter backup budget exceeded", "CAPACITY")
|
|
507
|
+
self.backups[site["name"]] = parameter.detach().clone()
|
|
508
|
+
kind, n = op["operation"], parameter.numel()
|
|
509
|
+
with self.torch.no_grad():
|
|
510
|
+
if kind == "WEIGHT_ADD":
|
|
511
|
+
delta = op["delta"]
|
|
512
|
+
value = number(delta["value"]) if delta["kind"] == "scalar" else self.tensor(delta["tensor"])
|
|
513
|
+
if not isinstance(value, (int, float)):
|
|
514
|
+
require(list(value.shape) == list(parameter.shape), "Weight addition shape mismatch")
|
|
515
|
+
self.charge(n)
|
|
516
|
+
if isinstance(value, (int, float)) and value == 0:
|
|
517
|
+
return
|
|
518
|
+
parameter.add_(value)
|
|
519
|
+
elif kind == "WEIGHT_GAIN":
|
|
520
|
+
gain = op["gain"]
|
|
521
|
+
if gain["kind"] == "scalar":
|
|
522
|
+
factor = number(gain["factor"])
|
|
523
|
+
if factor == 1:
|
|
524
|
+
return
|
|
525
|
+
else:
|
|
526
|
+
axis = integer(gain["axis"], 0, parameter.ndim - 1)
|
|
527
|
+
factor = self.tensor(gain["factors"])
|
|
528
|
+
require(list(factor.shape) == [parameter.shape[axis]], "Axis gain shape mismatch")
|
|
529
|
+
shape = [1] * parameter.ndim
|
|
530
|
+
shape[axis] = parameter.shape[axis]
|
|
531
|
+
factor = factor.reshape(shape)
|
|
532
|
+
self.charge(n)
|
|
533
|
+
parameter.mul_(factor)
|
|
534
|
+
elif kind == "WEIGHT_REPLACE":
|
|
535
|
+
value = self.tensor(op["replacement"])
|
|
536
|
+
require(list(value.shape) == list(parameter.shape), "Weight replacement shape mismatch")
|
|
537
|
+
self.charge(n)
|
|
538
|
+
parameter.copy_(value)
|
|
539
|
+
elif kind == "WEIGHT_PROJECT":
|
|
540
|
+
require(parameter.ndim == 2 and op["normalization"] == "orthonormal", "Projection requires an orthonormal matrix basis")
|
|
541
|
+
side = op["side"]
|
|
542
|
+
require(side in ("left", "right"), "Invalid projection side")
|
|
543
|
+
basis = self.basis(op["basis"], parameter.shape[0 if side == "left" else 1])
|
|
544
|
+
strength = number(op["strength"])
|
|
545
|
+
if strength == 0:
|
|
546
|
+
return
|
|
547
|
+
# Six dense float64 buffers conservatively cover conversions,
|
|
548
|
+
# both products, strength multiplication and final subtraction.
|
|
549
|
+
require(self.working_bytes + n * 48 <= self.limits["maxWorkingBytes"], "Projection workspace exceeds budget", "CAPACITY")
|
|
550
|
+
self.charge(5 * n * basis.shape[0])
|
|
551
|
+
value = parameter.to(self.torch.float64)
|
|
552
|
+
projected = basis.T @ (basis @ value) if side == "left" else (value @ basis.T) @ basis
|
|
553
|
+
parameter.copy_(value - strength * projected)
|
|
554
|
+
elif kind == "LOW_RANK_UPDATE":
|
|
555
|
+
require(parameter.ndim == 2 and op["scaling"] == "alpha_over_rank", "Unsupported low-rank semantics")
|
|
556
|
+
rank = integer(op["rank"], 1)
|
|
557
|
+
a, b = self.tensor(op["a"]), self.tensor(op["b"])
|
|
558
|
+
require(list(a.shape) == [rank, parameter.shape[1]] and list(b.shape) == [parameter.shape[0], rank], "Low-rank operand shape mismatch")
|
|
559
|
+
scale = number(op["scale"]) * (number(op["alpha"]) / rank)
|
|
560
|
+
number(scale)
|
|
561
|
+
if scale == 0:
|
|
562
|
+
return
|
|
563
|
+
require(self.working_bytes + n * 48 <= self.limits["maxWorkingBytes"], "Low-rank workspace exceeds budget", "CAPACITY")
|
|
564
|
+
self.charge(2 * n * rank + 2 * n)
|
|
565
|
+
parameter.copy_(parameter.to(self.torch.float64) + scale * (b @ a))
|
|
566
|
+
elif kind == "WEIGHT_MERGE":
|
|
567
|
+
# A JSON tensor claiming a checkpoint label cannot prove source
|
|
568
|
+
# identity. Dedicated source-checkpoint readers are not implicit.
|
|
569
|
+
raise Rejected("UNSUPPORTED", "Runtime weight merge requires a verified source-checkpoint reader")
|
|
570
|
+
require(bool(self.torch.isfinite(parameter).all()), "Weight edit produced nonfinite parameters")
|
|
571
|
+
|
|
572
|
+
def install(self, recipe):
|
|
573
|
+
if recipe is None:
|
|
574
|
+
return []
|
|
575
|
+
require(recipe.get("schema") == "omnius.nol.recipe.v1" and recipe["modelDigest"] == self.binding["modelDigest"] and
|
|
576
|
+
recipe["architectureMapDigest"] == self.binding["architectureMapDigest"], "Recipe/model binding mismatch", "IDENTITY")
|
|
577
|
+
operations = recipe["operations"]
|
|
578
|
+
require(type(operations) is list and 0 < len(operations) <= 1000, "Invalid bounded operation inventory")
|
|
579
|
+
require(len({op["id"] for op in operations}) == len(operations), "Duplicate operation ID")
|
|
580
|
+
require(not (any(op.get("operation") in PARAMETER_OPS for op in operations) and any(op.get("operation") in RUNTIME_OPS for op in operations)), "Mixed runtime/parameter ordering requires a separately validated lowering", "UNSUPPORTED")
|
|
581
|
+
groups, actual, storage = {}, [], {}
|
|
582
|
+
allowed = {
|
|
583
|
+
"NEURON_ADD": {"neuron", "amount", "units", "calibrationId"}, "NEURON_GAIN": {"neuron", "factor"},
|
|
584
|
+
"NEURON_REPLACE": {"neuron", "replacement", "units", "calibrationId"}, "RESIDUAL_ADD": {"vector", "scale", "units", "calibrationId"},
|
|
585
|
+
"DIRECTION_PROJECT": {"basis", "strength", "normalization"}, "WEIGHT_ADD": {"delta"}, "WEIGHT_GAIN": {"gain"},
|
|
586
|
+
"WEIGHT_REPLACE": {"replacement"}, "WEIGHT_PROJECT": {"side", "basis", "strength", "normalization"},
|
|
587
|
+
"LOW_RANK_UPDATE": {"a", "b", "rank", "alpha", "scale", "scaling"}}
|
|
588
|
+
for op in operations:
|
|
589
|
+
require(op.get("operation") in allowed, "Unsupported operation", "UNSUPPORTED")
|
|
590
|
+
require(set(op) <= {"id", "operation", "siteId", "tokenScope"} | allowed[op["operation"]], "Unknown operation field")
|
|
591
|
+
require("calibrationId" not in op and op.get("units", "raw") == "raw", "Only explicit raw-unit operands are implemented", "UNSUPPORTED")
|
|
592
|
+
site = self.sites.get(op["siteId"])
|
|
593
|
+
require(site is not None, "Unknown verified tensor site", "IDENTITY")
|
|
594
|
+
kind = op["operation"]
|
|
595
|
+
expected = "parameter" if kind in PARAMETER_OPS else "mlp_intermediate" if kind.startswith("NEURON_") else "residual"
|
|
596
|
+
require(site["kind"] == expected, "Operation/site type mismatch")
|
|
597
|
+
self.edited[op["id"]] = set()
|
|
598
|
+
actual.append({"operationId": op["id"], "operation": kind, "siteId": op["siteId"], "tokenScope": op["tokenScope"],
|
|
599
|
+
"implementation": WORKER_VERSION + ":" + kind, "equivalence": "exact"})
|
|
600
|
+
if kind in PARAMETER_OPS:
|
|
601
|
+
require(op["tokenScope"] == {"kind": "all"}, "Parameter edits have all-token semantics only", "UNSUPPORTED")
|
|
602
|
+
parameter = self.parameters[site["name"]]
|
|
603
|
+
pointer = parameter.data_ptr()
|
|
604
|
+
require(pointer not in storage or storage[pointer] == op["siteId"], "Overlapping tied-parameter aliases need explicit lowering", "UNSUPPORTED")
|
|
605
|
+
storage[pointer] = op["siteId"]
|
|
606
|
+
self.parameter_edit(op, site)
|
|
607
|
+
else:
|
|
608
|
+
prepared = dict(op)
|
|
609
|
+
if kind in ("NEURON_ADD", "NEURON_GAIN", "NEURON_REPLACE"):
|
|
610
|
+
integer(op["neuron"], 0, site["width"] - 1)
|
|
611
|
+
if kind == "RESIDUAL_ADD":
|
|
612
|
+
prepared["operand"] = self.tensor(op["vector"])
|
|
613
|
+
require(list(prepared["operand"].shape) == [site["width"]], "Residual vector width mismatch")
|
|
614
|
+
elif kind == "DIRECTION_PROJECT":
|
|
615
|
+
require(op["normalization"] == "orthonormal", "Unsupported projection normalization")
|
|
616
|
+
prepared["operand"] = self.basis(op["basis"], site["width"])
|
|
617
|
+
elif kind == "NEURON_REPLACE":
|
|
618
|
+
require(op["replacement"]["kind"] == "scalar", "Captured activation replacement is not implemented", "UNSUPPORTED")
|
|
619
|
+
groups.setdefault(op["siteId"], []).append(prepared)
|
|
620
|
+
for site_id, ops in groups.items():
|
|
621
|
+
site = self.sites[site_id]
|
|
622
|
+
layer = self.layers[site["layer"]]
|
|
623
|
+
def edit(value, selected=ops):
|
|
624
|
+
require(value.ndim == 3 and value.shape[0] == 1 and value.shape[1] == self.sequence_length, "Runtime hook shape changed", "IDENTITY")
|
|
625
|
+
require(self.working_bytes + value.numel() * (value.element_size() * 2 + 24) <= self.limits["maxWorkingBytes"], "Hook workspace exceeds budget", "CAPACITY")
|
|
626
|
+
result = value.clone()
|
|
627
|
+
for operation in selected:
|
|
628
|
+
positions = self.positions(operation["tokenScope"])
|
|
629
|
+
if not positions:
|
|
630
|
+
continue
|
|
631
|
+
kind = operation["operation"]
|
|
632
|
+
self.edited[operation["id"]].update(positions)
|
|
633
|
+
if kind.startswith("NEURON_"):
|
|
634
|
+
neuron = operation["neuron"]
|
|
635
|
+
current = result[:, positions, neuron]
|
|
636
|
+
self.charge(current.numel())
|
|
637
|
+
if kind == "NEURON_ADD":
|
|
638
|
+
amount = number(operation["amount"])
|
|
639
|
+
if amount != 0:
|
|
640
|
+
result[:, positions, neuron] = current + amount
|
|
641
|
+
elif kind == "NEURON_GAIN":
|
|
642
|
+
factor = number(operation["factor"])
|
|
643
|
+
if factor != 1:
|
|
644
|
+
result[:, positions, neuron] = current * factor
|
|
645
|
+
else:
|
|
646
|
+
result[:, positions, neuron] = number(operation["replacement"]["value"])
|
|
647
|
+
elif kind == "RESIDUAL_ADD":
|
|
648
|
+
scale = number(operation["scale"])
|
|
649
|
+
if scale != 0:
|
|
650
|
+
self.charge(2 * len(positions) * value.shape[-1])
|
|
651
|
+
result[:, positions, :] = result[:, positions, :] + scale * operation["operand"].to(value.dtype)
|
|
652
|
+
else:
|
|
653
|
+
strength = number(operation["strength"])
|
|
654
|
+
if strength != 0:
|
|
655
|
+
basis = operation["operand"]
|
|
656
|
+
self.charge(5 * len(positions) * value.shape[-1] * basis.shape[0])
|
|
657
|
+
current = result[:, positions, :].to(self.torch.float64)
|
|
658
|
+
result[:, positions, :] = (current - strength * ((current @ basis.T) @ basis)).to(value.dtype)
|
|
659
|
+
require(bool(self.torch.isfinite(result).all()), "Hook produced a nonfinite activation")
|
|
660
|
+
return result
|
|
661
|
+
if site["kind"] == "mlp_intermediate":
|
|
662
|
+
self.hooks.append(layer.mlp.down_proj.register_forward_pre_hook(lambda module, args, fn=edit: (fn(args[0]), *args[1:])))
|
|
663
|
+
else:
|
|
664
|
+
self.hooks.append(layer.register_forward_hook(lambda module, args, output, fn=edit: fn(output)))
|
|
665
|
+
return actual
|
|
666
|
+
|
|
667
|
+
def generate(self, payload):
|
|
668
|
+
self.ready()
|
|
669
|
+
fields(payload, ("messages", "recipe", "recipeIdentityJson", "cacheKeyDigest", "seed", "maxTokens", "decoding"))
|
|
670
|
+
require(not self.hooks and not self.backups and self.cache_key is None, "Worker requires a clean reset", "RESET")
|
|
671
|
+
maximum = integer(payload["maxTokens"], 1, self.limits["maxOutputTokens"])
|
|
672
|
+
seed = integer(payload["seed"], 0, 4294967295)
|
|
673
|
+
require(SHA.fullmatch(payload["cacheKeyDigest"]), "Invalid cold cache identity")
|
|
674
|
+
decoding = payload["decoding"]
|
|
675
|
+
fields(decoding, ("temperature", "topP", "topK", "constrainedDecoding"))
|
|
676
|
+
temperature, top_p, top_k = number(decoding["temperature"]), number(decoding["topP"]), integer(decoding["topK"])
|
|
677
|
+
require(temperature >= 0 and 0 < top_p <= 1 and decoding["constrainedDecoding"] == "none", "Unsupported sampling or constrained decoding", "UNSUPPORTED")
|
|
678
|
+
prompt = self.tokenize({"messages": payload["messages"]})["tokenIds"]
|
|
679
|
+
require(len(prompt) + maximum <= self.binding["contextLimit"], "Physical context limit exceeded", "CAPACITY")
|
|
680
|
+
if payload["recipe"] is not None:
|
|
681
|
+
recipe = payload["recipe"]
|
|
682
|
+
verify_identity(payload["recipeIdentityJson"], {key: value for key, value in recipe.items() if key != "recipeDigest"}, recipe["recipeDigest"])
|
|
683
|
+
else:
|
|
684
|
+
require(payload["recipeIdentityJson"] is None, "Baseline cannot carry a recipe identity")
|
|
685
|
+
require(self.last_reset is not None, "Explicit host reset is required before generation", "RESET")
|
|
686
|
+
before = self.last_reset
|
|
687
|
+
self.prompt_length = len(prompt)
|
|
688
|
+
self.cache_key = payload["cacheKeyDigest"]
|
|
689
|
+
outputs, actual = [], []
|
|
690
|
+
self.torch.manual_seed(seed)
|
|
691
|
+
self.torch.cuda.manual_seed_all(seed)
|
|
692
|
+
try:
|
|
693
|
+
actual = self.install(payload["recipe"])
|
|
694
|
+
with self.torch.inference_mode():
|
|
695
|
+
for _ in range(maximum):
|
|
696
|
+
self.sequence_length = len(prompt) + len(outputs)
|
|
697
|
+
ids = self.torch.tensor([prompt + outputs], device="cuda:0", dtype=self.torch.long)
|
|
698
|
+
result = self.model(input_ids=ids, attention_mask=self.torch.ones_like(ids), use_cache=False, logits_to_keep=1)
|
|
699
|
+
require(result.past_key_values is None, "Runtime retained an unadvertised cache", "RESET")
|
|
700
|
+
logits = result.logits[0, -1].float()
|
|
701
|
+
require(bool(self.torch.isfinite(logits).all()), "Model produced nonfinite logits")
|
|
702
|
+
if temperature == 0:
|
|
703
|
+
token = int(logits.argmax().item())
|
|
704
|
+
else:
|
|
705
|
+
logits = logits / temperature
|
|
706
|
+
if 0 < top_k < logits.numel():
|
|
707
|
+
logits[logits < self.torch.topk(logits, top_k).values[-1]] = -self.torch.inf
|
|
708
|
+
sorted_logits, order = self.torch.sort(logits, descending=True)
|
|
709
|
+
probabilities = self.torch.softmax(sorted_logits, dim=-1)
|
|
710
|
+
mask = probabilities.cumsum(-1) - probabilities > top_p
|
|
711
|
+
sorted_logits[mask] = -self.torch.inf
|
|
712
|
+
picked = self.torch.multinomial(self.torch.softmax(sorted_logits, -1), 1)
|
|
713
|
+
token = int(order[picked].item())
|
|
714
|
+
outputs.append(token)
|
|
715
|
+
del result, ids, logits
|
|
716
|
+
if token == self.tokenizer.eos_token_id:
|
|
717
|
+
break
|
|
718
|
+
require(len(self.tokenizer.decode(outputs).encode()) < MAX_FRAME // 2, "Output byte budget exceeded", "CAPACITY")
|
|
719
|
+
text = self.tokenizer.decode(outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
|
720
|
+
observed = {key: sorted(value) for key, value in self.edited.items()}
|
|
721
|
+
for operation in actual:
|
|
722
|
+
if operation["operation"] in PARAMETER_OPS:
|
|
723
|
+
observed[operation["operationId"]] = list(range(len(prompt) + max(0, len(outputs) - 1)))
|
|
724
|
+
reset = self.reset()
|
|
725
|
+
return {"text": text, "promptTokenIds": prompt, "tokenIds": outputs,
|
|
726
|
+
"usage": {"promptTokens": len(prompt), "completionTokens": len(outputs)},
|
|
727
|
+
"finishReason": "stop" if outputs and outputs[-1] == self.tokenizer.eos_token_id else "length",
|
|
728
|
+
"native": {"binding": self.binding, "implementation": WORKER_VERSION, "operations": actual,
|
|
729
|
+
"editedPositions": observed, "cacheKeyDigest": payload["cacheKeyDigest"],
|
|
730
|
+
"resetBefore": before, "resetAfter": reset, "usesCache": False,
|
|
731
|
+
"recipeDigest": payload["recipe"]["recipeDigest"] if payload["recipe"] else None}}
|
|
732
|
+
except BaseException:
|
|
733
|
+
try:
|
|
734
|
+
self.reset()
|
|
735
|
+
except BaseException as error:
|
|
736
|
+
raise Rejected("RESET", "Failed trial could not restore clean state", True) from error
|
|
737
|
+
raise
|
|
738
|
+
|
|
739
|
+
def profile(self, payload):
|
|
740
|
+
"""One real forward pass, bounded coordinate moments, no sampled tokens."""
|
|
741
|
+
self.ready()
|
|
742
|
+
fields(payload, ("messages", "recipe", "recipeIdentityJson", "sourceArtifact", "capture"))
|
|
743
|
+
require(not self.hooks and not self.backups and self.last_reset is not None and self.cache_key is None, "Profile requires an explicit clean host reset", "RESET")
|
|
744
|
+
source = payload["sourceArtifact"]
|
|
745
|
+
fields(source, ("uri", "sha256", "sizeBytes", "mediaType"))
|
|
746
|
+
require(SHA.fullmatch(source["sha256"]) and source["uri"] == "omnius-artifact://sha256/" + source["sha256"], "Invalid profile source artifact")
|
|
747
|
+
require(source["mediaType"] == "application/json", "Profile source must be a versioned JSON input")
|
|
748
|
+
source_path = safe_path(self.artifact_root, source["sha256"][:2] + "/" + source["sha256"])
|
|
749
|
+
require(hash_file(source_path, self.limits["maxTensorBytes"]) == {"sha256": source["sha256"], "sizeBytes": source["sizeBytes"]}, "Profile source artifact changed", "IDENTITY")
|
|
750
|
+
with source_path.open("rb") as source_stream:
|
|
751
|
+
source_bytes = source_stream.read(source["sizeBytes"] + 1)
|
|
752
|
+
require(len(source_bytes) == source["sizeBytes"] and digest_bytes(source_bytes) == source["sha256"], "Profile source changed before parsing", "IDENTITY")
|
|
753
|
+
source_input = parse_json(source_bytes.decode("utf-8", "strict"))
|
|
754
|
+
fields(source_input, ("schema", "messages"))
|
|
755
|
+
require(source_input["schema"] == "omnius.nol.profile-input.v1" and same_json(source_input["messages"], payload["messages"]),
|
|
756
|
+
"Profile messages differ from the exact versioned source artifact", "IDENTITY")
|
|
757
|
+
capture = payload["capture"]
|
|
758
|
+
fields(capture, ("sites", "maxPositions", "maxCoordinates"))
|
|
759
|
+
positions_limit = integer(capture["maxPositions"], 1, min(4096, self.limits["maxInputTokens"]))
|
|
760
|
+
coordinate_limit = integer(capture["maxCoordinates"], 1, 1024)
|
|
761
|
+
require(type(capture["sites"]) is list and 0 < len(capture["sites"]) <= 16, "Invalid profile site budget", "CAPACITY")
|
|
762
|
+
selected, coordinates = {}, 0
|
|
763
|
+
for spec in capture["sites"]:
|
|
764
|
+
fields(spec, ("siteId", "indices"))
|
|
765
|
+
site = self.sites.get(spec["siteId"])
|
|
766
|
+
require(site and site["kind"] in ("mlp_intermediate", "residual") and spec["siteId"] not in selected, "Unknown or duplicate profile site", "UNSUPPORTED")
|
|
767
|
+
require(type(spec["indices"]) is list and 0 < len(spec["indices"]) <= 1024 and len(spec["indices"]) == len(set(spec["indices"])), "Invalid profile coordinates")
|
|
768
|
+
for index in spec["indices"]:
|
|
769
|
+
integer(index, 0, site["width"] - 1)
|
|
770
|
+
coordinates += len(spec["indices"])
|
|
771
|
+
selected[spec["siteId"]] = spec
|
|
772
|
+
require(coordinates <= coordinate_limit, "Profile coordinate budget exceeded", "CAPACITY")
|
|
773
|
+
prompt = self.tokenize({"messages": payload["messages"]})["tokenIds"]
|
|
774
|
+
if payload["recipe"] is not None:
|
|
775
|
+
verify_identity(payload["recipeIdentityJson"], {key: value for key, value in payload["recipe"].items() if key != "recipeDigest"}, payload["recipe"]["recipeDigest"])
|
|
776
|
+
else:
|
|
777
|
+
require(payload["recipeIdentityJson"] is None, "Baseline profile carries a recipe identity")
|
|
778
|
+
before, observed = self.last_reset, {}
|
|
779
|
+
self.prompt_length = self.sequence_length = len(prompt)
|
|
780
|
+
try:
|
|
781
|
+
actual = self.install(payload["recipe"])
|
|
782
|
+
for site_id, spec in selected.items():
|
|
783
|
+
site, indices = self.sites[site_id], spec["indices"]
|
|
784
|
+
def collect(value, key=site_id, columns=indices, kind=site["kind"]):
|
|
785
|
+
require(key not in observed and value.ndim == 3 and value.shape[0] == 1 and value.shape[1] == len(prompt), "Profile hook shape/call count changed", "IDENTITY")
|
|
786
|
+
count = min(value.shape[1], positions_limit)
|
|
787
|
+
require(self.working_bytes + count * len(columns) * 64 <= self.limits["maxWorkingBytes"], "Profile workspace exceeds budget", "CAPACITY")
|
|
788
|
+
self.charge(count * len(columns) * 16)
|
|
789
|
+
index = self.torch.tensor(columns, dtype=self.torch.long, device=value.device)
|
|
790
|
+
sample = value[0, :count, :].index_select(1, index).to(self.torch.float64)
|
|
791
|
+
require(bool(self.torch.isfinite(sample).all()), "Profile captured nonfinite activations")
|
|
792
|
+
mean = sample.mean(dim=0)
|
|
793
|
+
variance = ((sample - mean) ** 2).mean(dim=0)
|
|
794
|
+
observed[key] = {"siteId": key, "siteKind": kind, "indices": columns, "count": count,
|
|
795
|
+
"mean": mean.tolist(), "std": variance.sqrt().tolist(),
|
|
796
|
+
"rms": (sample.square().mean(dim=0)).sqrt().tolist(),
|
|
797
|
+
"minimum": sample.amin(dim=0).tolist(), "maximum": sample.amax(dim=0).tolist()}
|
|
798
|
+
layer = self.layers[site["layer"]]
|
|
799
|
+
if site["kind"] == "mlp_intermediate":
|
|
800
|
+
def pre(module, args, fn=collect):
|
|
801
|
+
fn(args[0])
|
|
802
|
+
self.hooks.append(layer.mlp.down_proj.register_forward_pre_hook(pre))
|
|
803
|
+
else:
|
|
804
|
+
def post(module, args, output, fn=collect):
|
|
805
|
+
fn(output)
|
|
806
|
+
self.hooks.append(layer.register_forward_hook(post))
|
|
807
|
+
with self.torch.inference_mode():
|
|
808
|
+
ids = self.torch.tensor([prompt], device="cuda:0", dtype=self.torch.long)
|
|
809
|
+
result = self.model(input_ids=ids, attention_mask=self.torch.ones_like(ids), use_cache=False, logits_to_keep=1)
|
|
810
|
+
require(result.past_key_values is None and len(observed) == len(selected), "Profile did not execute every selected hook cleanly", "RESET")
|
|
811
|
+
del result, ids
|
|
812
|
+
positions = {key: sorted(value) for key, value in self.edited.items()}
|
|
813
|
+
after = self.reset()
|
|
814
|
+
return {"sourceArtifact": source, "promptTokenIds": prompt, "promptTokens": len(prompt), "sampledTokens": 0,
|
|
815
|
+
"observationUnit": "single_forward_computation_positions", "summaries": list(observed.values()),
|
|
816
|
+
"native": {"binding": self.binding, "implementation": WORKER_VERSION, "operations": actual,
|
|
817
|
+
"editedPositions": positions, "resetBefore": before, "resetAfter": after, "usesCache": False}}
|
|
818
|
+
except BaseException:
|
|
819
|
+
try:
|
|
820
|
+
self.reset()
|
|
821
|
+
except BaseException as error:
|
|
822
|
+
raise Rejected("RESET", "Profile could not restore clean state", True) from error
|
|
823
|
+
raise
|
|
824
|
+
|
|
825
|
+
def close(self):
|
|
826
|
+
if self.model is not None:
|
|
827
|
+
self.reset()
|
|
828
|
+
self.model = self.tokenizer = None
|
|
829
|
+
self.parameters = self.layers = self.sites = None
|
|
830
|
+
gc.collect()
|
|
831
|
+
if self.torch is not None:
|
|
832
|
+
self.torch.cuda.synchronize()
|
|
833
|
+
self.torch.cuda.empty_cache()
|
|
834
|
+
self.loaded = self.confirmed = False
|
|
835
|
+
return {"closed": True, "pid": os.getpid(), "allocationReleaseRequiresHostVerification": True}
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def read_exact(stream, count):
|
|
839
|
+
data = bytearray()
|
|
840
|
+
while len(data) < count:
|
|
841
|
+
part = stream.read(count - len(data))
|
|
842
|
+
if not part:
|
|
843
|
+
require(not data, "Truncated worker frame")
|
|
844
|
+
return None
|
|
845
|
+
data.extend(part)
|
|
846
|
+
return bytes(data)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def serve():
|
|
850
|
+
sys.stdout = sys.stderr # Native libraries and warnings cannot corrupt framing.
|
|
851
|
+
require(0 < MAX_FRAME <= 67108864 and all(OWNER[key] for key in OWNER) and type(OWNER["generation"]) is int,
|
|
852
|
+
"Missing private worker ownership environment")
|
|
853
|
+
runtime, sequence = Runtime(), 0
|
|
854
|
+
while True:
|
|
855
|
+
header = read_exact(sys.stdin.buffer, 4)
|
|
856
|
+
if header is None:
|
|
857
|
+
break
|
|
858
|
+
size = struct.unpack(">I", header)[0]
|
|
859
|
+
require(0 < size <= MAX_FRAME, "Worker input frame exceeds byte limit", "CAPACITY")
|
|
860
|
+
raw = read_exact(sys.stdin.buffer, size)
|
|
861
|
+
require(raw is not None, "Truncated worker request")
|
|
862
|
+
request = parse_json(raw.decode("utf-8", "strict"))
|
|
863
|
+
fields(request, ("schema", "kind", "sessionId", "jobId", "ownerId", "generation", "id", "action", "payload"))
|
|
864
|
+
require(request["schema"] == PROTOCOL and request["kind"] == "request" and
|
|
865
|
+
all(request[key] == value for key, value in OWNER.items()) and request["id"] == sequence + 1,
|
|
866
|
+
"Worker request ownership/sequence mismatch", "IDENTITY")
|
|
867
|
+
sequence += 1
|
|
868
|
+
response = {key: request[key] for key in ("schema", "sessionId", "jobId", "ownerId", "generation", "id", "action")}
|
|
869
|
+
response["kind"] = "response"
|
|
870
|
+
closing = False
|
|
871
|
+
try:
|
|
872
|
+
action, payload = request["action"], request["payload"]
|
|
873
|
+
if action == "hello":
|
|
874
|
+
fields(payload, ())
|
|
875
|
+
result = {"protocol": PROTOCOL, "workerVersion": WORKER_VERSION, "pid": os.getpid(), "workerSha256": hash_file(Path(__file__).resolve())["sha256"],
|
|
876
|
+
"pythonVersion": sys.version.split()[0], "loaded": runtime.loaded, "torchImported": "torch" in sys.modules}
|
|
877
|
+
elif action == "inspect":
|
|
878
|
+
result = runtime.inspect(payload)
|
|
879
|
+
elif action == "load":
|
|
880
|
+
result = runtime.load(payload)
|
|
881
|
+
elif action == "confirm_placement":
|
|
882
|
+
result = runtime.confirm(payload)
|
|
883
|
+
elif action == "tokenize":
|
|
884
|
+
result = runtime.tokenize(payload)
|
|
885
|
+
elif action == "reset":
|
|
886
|
+
fields(payload, ())
|
|
887
|
+
result = runtime.reset()
|
|
888
|
+
elif action == "generate":
|
|
889
|
+
result = runtime.generate(payload)
|
|
890
|
+
elif action == "profile":
|
|
891
|
+
result = runtime.profile(payload)
|
|
892
|
+
elif action == "close":
|
|
893
|
+
fields(payload, ())
|
|
894
|
+
result, closing = runtime.close(), True
|
|
895
|
+
else:
|
|
896
|
+
raise Rejected("UNSUPPORTED", "Unknown worker command")
|
|
897
|
+
response["result"] = result
|
|
898
|
+
except Rejected as error:
|
|
899
|
+
closing = error.fatal or action == "load"
|
|
900
|
+
response["error"] = {"code": error.code, "message": str(error)[:4096], "fatal": closing}
|
|
901
|
+
except BaseException as error:
|
|
902
|
+
private_diagnostic(error)
|
|
903
|
+
# No model text, arbitrary traceback or local paths enter protocol errors.
|
|
904
|
+
response["error"] = {"code": "RUNTIME_FAILURE", "message": type(error).__name__, "fatal": True}
|
|
905
|
+
closing = True
|
|
906
|
+
body = json.dumps(response, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
907
|
+
require(len(body) <= MAX_FRAME, "Worker response frame exceeds byte limit", "CAPACITY")
|
|
908
|
+
WIRE_OUT.write(struct.pack(">I", len(body)) + body)
|
|
909
|
+
WIRE_OUT.flush()
|
|
910
|
+
if closing:
|
|
911
|
+
break
|
|
912
|
+
runtime.close()
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
if __name__ == "__main__":
|
|
916
|
+
try:
|
|
917
|
+
serve()
|
|
918
|
+
except BaseException as error:
|
|
919
|
+
sys.stderr.write("NOL worker retired: " + type(error).__name__ + "\n")
|
|
920
|
+
sys.exit(1)
|