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,785 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Bounded CPU-only GGUF parameter export. No model/native runtime is loaded.
|
|
3
|
+
|
|
4
|
+
GGUF codecs are supplied by an explicitly pinned gguf/NumPy installation; this
|
|
5
|
+
file contains original bounded parsing/publication logic, not vendored GNE code.
|
|
6
|
+
Operations run in declared order at IEEE float64 reference precision, followed
|
|
7
|
+
by one storage encode per changed tensor. This is never native equivalence.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
import ctypes
|
|
11
|
+
import hashlib
|
|
12
|
+
import importlib.metadata
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import platform
|
|
18
|
+
import re
|
|
19
|
+
import signal
|
|
20
|
+
import stat
|
|
21
|
+
import struct
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
|
|
25
|
+
OPS = {"WEIGHT_ADD", "WEIGHT_GAIN", "WEIGHT_REPLACE", "WEIGHT_PROJECT", "LOW_RANK_UPDATE", "WEIGHT_MERGE"}
|
|
26
|
+
SUPPORTED = {"F32", "F16", "BF16", "Q4_0", "Q8_0", "Q4_K", "Q6_K"}
|
|
27
|
+
FLOATS = {"f16": "<f2", "f32": "<f4", "f64": "<f8"}
|
|
28
|
+
MAX_FRAME = 16 * 1024 * 1024
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def need(ok, message):
|
|
32
|
+
if not ok:
|
|
33
|
+
raise ValueError(message)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def integer(value, minimum=0, maximum=9007199254740991):
|
|
37
|
+
need(type(value) is int and minimum <= value <= maximum, "Invalid bounded integer")
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def finite(value):
|
|
42
|
+
need(type(value) in (int, float) and math.isfinite(value), "Nonfinite scalar")
|
|
43
|
+
return float(value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def fields(value, required, optional=()):
|
|
47
|
+
need(type(value) is dict and set(required) <= value.keys() <= set(required) | set(optional), "Unexpected/missing protocol fields")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def pairs(items):
|
|
51
|
+
result = {}
|
|
52
|
+
for key, value in items:
|
|
53
|
+
need(key not in result, "Duplicate JSON key")
|
|
54
|
+
result[key] = value
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse(raw):
|
|
59
|
+
return json.loads(raw, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def encoded(value):
|
|
63
|
+
return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def digest(raw):
|
|
67
|
+
return hashlib.sha256(raw).hexdigest()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def same(a, b):
|
|
71
|
+
if type(a) in (int, float) and type(b) in (int, float):
|
|
72
|
+
return a == b and (a != 0 or math.copysign(1, a) == math.copysign(1, b))
|
|
73
|
+
if type(a) is not type(b):
|
|
74
|
+
return False
|
|
75
|
+
if type(a) is dict:
|
|
76
|
+
return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
|
|
77
|
+
if type(a) is list:
|
|
78
|
+
return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
|
|
79
|
+
return a == b
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Budget:
|
|
83
|
+
def __init__(self, limits):
|
|
84
|
+
names = ("maxInputBytes", "maxArtifactBytes", "maxOutputBytes", "maxWorkingBytes", "maxArithmeticUnits", "maxOperations", "maxDurationMs", "maxProtocolBytes", "maxMetadataBytes", "maxTensors", "maxKeyValues", "maxArrayElements")
|
|
85
|
+
fields(limits, names)
|
|
86
|
+
for value in limits.values():
|
|
87
|
+
integer(value, 1)
|
|
88
|
+
need(limits["maxProtocolBytes"] <= MAX_FRAME and limits["maxMetadataBytes"] <= 256 * 1024 ** 2 and limits["maxDurationMs"] <= 86400000 and limits["maxTensors"] <= 100000 and limits["maxKeyValues"] <= 100000 and limits["maxArrayElements"] <= 10000000, "Unsupported absolute admission bound")
|
|
89
|
+
self.limits = limits
|
|
90
|
+
self.started = time.monotonic()
|
|
91
|
+
self.deadline = self.started + limits["maxDurationMs"] / 1000
|
|
92
|
+
self.input = self.artifacts = self.working = self.arithmetic = 0
|
|
93
|
+
self.verified = {}
|
|
94
|
+
self.inputHashes, self.artifactHashes = set(), set()
|
|
95
|
+
self.reserve(262144)
|
|
96
|
+
|
|
97
|
+
def check(self):
|
|
98
|
+
need(time.monotonic() <= self.deadline, "GGUF wall budget exceeded")
|
|
99
|
+
|
|
100
|
+
def reserve(self, count):
|
|
101
|
+
self.check()
|
|
102
|
+
self.working += integer(count)
|
|
103
|
+
need(self.working <= self.limits["maxWorkingBytes"], "GGUF cumulative tensor/workspace reservation exceeded")
|
|
104
|
+
|
|
105
|
+
def work(self, count):
|
|
106
|
+
self.check()
|
|
107
|
+
self.arithmetic += integer(count)
|
|
108
|
+
need(self.arithmetic <= self.limits["maxArithmeticUnits"], "GGUF arithmetic budget exceeded")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def regular(path):
|
|
112
|
+
need(path.is_absolute(), "Explicit absolute file required")
|
|
113
|
+
current = Path(path.anchor)
|
|
114
|
+
for part in path.parts[1:]:
|
|
115
|
+
current /= part
|
|
116
|
+
need(not current.is_symlink(), "Symlink component refused")
|
|
117
|
+
info = path.lstat()
|
|
118
|
+
need(stat.S_ISREG(info.st_mode), "Nonsymlink regular file required")
|
|
119
|
+
return info
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def safe(root, name):
|
|
123
|
+
need(type(name) is str and name and "\\" not in name and "\0" not in name and not name.startswith("/") and all(x not in ("", ".", "..") for x in name.split("/")), "Unsafe relative file path")
|
|
124
|
+
path = root / name
|
|
125
|
+
regular(path)
|
|
126
|
+
return path
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def hash_file(path, budget=None):
|
|
130
|
+
before = regular(path)
|
|
131
|
+
h, size = hashlib.sha256(), 0
|
|
132
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
133
|
+
try:
|
|
134
|
+
opened = os.fstat(fd)
|
|
135
|
+
need((opened.st_dev, opened.st_ino) == (before.st_dev, before.st_ino), "Source inode changed before open")
|
|
136
|
+
with os.fdopen(fd, "rb", closefd=False) as f:
|
|
137
|
+
while True:
|
|
138
|
+
if budget:
|
|
139
|
+
budget.check()
|
|
140
|
+
block = f.read(65536)
|
|
141
|
+
if not block:
|
|
142
|
+
break
|
|
143
|
+
h.update(block)
|
|
144
|
+
size += len(block)
|
|
145
|
+
after = os.fstat(fd)
|
|
146
|
+
need((opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) == (after.st_size, after.st_mtime_ns, after.st_ctime_ns) and size == opened.st_size, "File changed while hashing")
|
|
147
|
+
finally:
|
|
148
|
+
os.close(fd)
|
|
149
|
+
return {"sha256": h.hexdigest(), "sizeBytes": size}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def range_hash(path, start, size, budget):
|
|
153
|
+
h = hashlib.sha256()
|
|
154
|
+
with path.open("rb") as stream:
|
|
155
|
+
stream.seek(start)
|
|
156
|
+
while size:
|
|
157
|
+
budget.check()
|
|
158
|
+
block = stream.read(min(size, 65536))
|
|
159
|
+
need(block, "Truncated tensor extent")
|
|
160
|
+
h.update(block)
|
|
161
|
+
size -= len(block)
|
|
162
|
+
return h.hexdigest()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def runtime_inventory(lock):
|
|
166
|
+
# Import only pure GGUF codecs plus NumPy. Never import GNE, Torch, llama.cpp.
|
|
167
|
+
import numpy as np
|
|
168
|
+
import gguf
|
|
169
|
+
packages = []
|
|
170
|
+
total = 0
|
|
171
|
+
for name in ("numpy", "gguf"):
|
|
172
|
+
distribution = importlib.metadata.distribution(name)
|
|
173
|
+
files = []
|
|
174
|
+
for item in sorted(distribution.files or (), key=str):
|
|
175
|
+
text = str(item)
|
|
176
|
+
if "__pycache__" in text or text.endswith((".pyc", ".pyo")):
|
|
177
|
+
continue
|
|
178
|
+
# Complete package, bundled numeric libraries and distribution pins.
|
|
179
|
+
if not (text.startswith(name + "/") or text.startswith(name + ".libs/") or ".dist-info/" in text):
|
|
180
|
+
continue
|
|
181
|
+
path = Path(distribution.locate_file(item)).resolve(strict=True)
|
|
182
|
+
info = regular(path)
|
|
183
|
+
total += info.st_size
|
|
184
|
+
need(total <= 512 * 1024 ** 2 and len(files) < 50000, "Runtime dependency inventory bound exceeded")
|
|
185
|
+
files.append({"path": text, **hash_file(path)})
|
|
186
|
+
need(files, "Missing package runtime inventory")
|
|
187
|
+
packages.append({"name": name, "version": distribution.version, "files": files})
|
|
188
|
+
need(importlib.metadata.version("gguf") == "0.19.0", "Unsupported GGUF codec version")
|
|
189
|
+
need(not any(n.startswith(("torch", "llama_cpp", "gne.runtime")) for n in sys.modules), "Native/model runtime unexpectedly imported")
|
|
190
|
+
body = {"schema": "omnius.nol.gguf-editor-runtime.v1", "pythonVersion": platform.python_version(), "pythonExecutable": hash_file(Path(sys.executable).resolve(strict=True)), "packages": packages, "dependencyLock": hash_file(Path(lock))}
|
|
191
|
+
return {**body, "runtimeDigest": digest(encoded(body))}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class Scanner:
|
|
195
|
+
def __init__(self, path, budget):
|
|
196
|
+
from gguf.constants import GGML_QUANT_SIZES, GGMLQuantizationType
|
|
197
|
+
self.path, self.budget = path, budget
|
|
198
|
+
self.size = regular(path).st_size
|
|
199
|
+
self.stream = path.open("rb")
|
|
200
|
+
self.off, self.arrays = 0, 0
|
|
201
|
+
self.keys, self.tensors = {}, []
|
|
202
|
+
try:
|
|
203
|
+
need(self.read(4) == b"GGUF", "Bad GGUF magic")
|
|
204
|
+
self.version = self.u("I")
|
|
205
|
+
need(self.version == 3, "Only little-endian GGUF v3 is supported")
|
|
206
|
+
tensors, kv = self.u("Q"), self.u("Q")
|
|
207
|
+
need(0 < tensors <= budget.limits["maxTensors"] and kv <= budget.limits["maxKeyValues"], "GGUF directory count bound exceeded")
|
|
208
|
+
for _ in range(kv):
|
|
209
|
+
key = self.string()
|
|
210
|
+
need(key and key not in self.keys and not key.startswith("split."), "Duplicate/empty key or split GGUF unsupported")
|
|
211
|
+
kind = self.u("I")
|
|
212
|
+
value = self.value(kind)
|
|
213
|
+
self.keys[key] = (kind, value)
|
|
214
|
+
self.metadataEnd = self.off
|
|
215
|
+
alignment = self.keys.get("general.alignment", (4, 32))
|
|
216
|
+
need(alignment[0] == 4 and type(alignment[1]) is int and 0 < alignment[1] <= 1048576 and alignment[1] & (alignment[1] - 1) == 0, "Invalid GGUF alignment")
|
|
217
|
+
self.alignment = alignment[1]
|
|
218
|
+
need(self.keys.get("general.architecture", (None, None))[0] == 8, "Missing architecture metadata")
|
|
219
|
+
names = set()
|
|
220
|
+
for _ in range(tensors):
|
|
221
|
+
name = self.string()
|
|
222
|
+
need(name and len(name.encode()) <= 4096 and name not in names, "Duplicate/unsafe tensor name")
|
|
223
|
+
names.add(name)
|
|
224
|
+
ndim = self.u("I")
|
|
225
|
+
need(1 <= ndim <= 4, "Unsupported GGUF tensor rank")
|
|
226
|
+
ne = [integer(self.u("Q"), 1) for _ in range(ndim)]
|
|
227
|
+
elements = math.prod(ne)
|
|
228
|
+
integer(elements, 1)
|
|
229
|
+
typeOffset = self.off
|
|
230
|
+
rawType = self.u("I")
|
|
231
|
+
try:
|
|
232
|
+
qtype = GGMLQuantizationType(rawType)
|
|
233
|
+
block, width = GGML_QUANT_SIZES[qtype]
|
|
234
|
+
except (ValueError, KeyError):
|
|
235
|
+
raise ValueError("Unknown GGUF storage block type")
|
|
236
|
+
need(ne[0] % block == 0, "GGUF row is not aligned to its storage block")
|
|
237
|
+
offsetField = self.off
|
|
238
|
+
offset = self.u("Q")
|
|
239
|
+
size = elements // block * width
|
|
240
|
+
need(offset % self.alignment == 0 and size > 0, "Unaligned/empty GGUF tensor")
|
|
241
|
+
self.tensors.append({"name": name, "ne": ne, "shape": list(reversed(ne)), "qtype": qtype.name, "typeId": rawType, "typeOffset": typeOffset, "offsetField": offsetField, "relativeOffset": offset, "sizeBytes": size, "elements": elements})
|
|
242
|
+
self.directoryEnd = self.off
|
|
243
|
+
self.dataStart = (self.off + self.alignment - 1) // self.alignment * self.alignment
|
|
244
|
+
need(self.dataStart <= budget.limits["maxMetadataBytes"] and self.dataStart <= self.size, "GGUF header byte bound exceeded")
|
|
245
|
+
previous = self.dataStart
|
|
246
|
+
for tensor in sorted(self.tensors, key=lambda t: t["relativeOffset"]):
|
|
247
|
+
start = self.dataStart + tensor["relativeOffset"]
|
|
248
|
+
need(start >= previous and start + tensor["sizeBytes"] <= self.size, "Overlapping/aliased/truncated tensor extent")
|
|
249
|
+
tensor["dataOffset"] = start
|
|
250
|
+
previous = start + tensor["sizeBytes"]
|
|
251
|
+
self.byName = {t["name"]: t for t in self.tensors}
|
|
252
|
+
# Account independent official reader's bounded metadata object graph.
|
|
253
|
+
budget.reserve(self.dataStart * 4 + self.arrays * 1024 + len(self.tensors) * 2048)
|
|
254
|
+
finally:
|
|
255
|
+
self.stream.close()
|
|
256
|
+
|
|
257
|
+
def read(self, size):
|
|
258
|
+
self.budget.check()
|
|
259
|
+
need(type(size) is int and size >= 0 and self.off + size <= min(self.size, self.budget.limits["maxMetadataBytes"]), "GGUF header extent exceeds bounds")
|
|
260
|
+
raw = self.stream.read(size)
|
|
261
|
+
need(len(raw) == size, "Truncated GGUF directory")
|
|
262
|
+
self.off += size
|
|
263
|
+
return raw
|
|
264
|
+
|
|
265
|
+
def u(self, fmt):
|
|
266
|
+
return struct.unpack("<" + fmt, self.read(struct.calcsize("<" + fmt)))[0]
|
|
267
|
+
|
|
268
|
+
def string(self):
|
|
269
|
+
size = self.u("Q")
|
|
270
|
+
need(size <= 1048576, "GGUF string bound exceeded")
|
|
271
|
+
return self.read(size).decode("utf-8", "strict")
|
|
272
|
+
|
|
273
|
+
def value(self, kind):
|
|
274
|
+
scalar = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "B", 10: "Q", 11: "q", 12: "d"}
|
|
275
|
+
if kind == 8:
|
|
276
|
+
return self.string()
|
|
277
|
+
if kind in scalar:
|
|
278
|
+
value = self.u(scalar[kind])
|
|
279
|
+
need(kind != 7 or value in (0, 1), "Invalid GGUF boolean")
|
|
280
|
+
return value
|
|
281
|
+
need(kind == 9, "Unknown metadata type")
|
|
282
|
+
subtype, count = self.u("I"), self.u("Q")
|
|
283
|
+
self.arrays += count
|
|
284
|
+
need(self.arrays <= self.budget.limits["maxArrayElements"] and subtype in set(scalar) | {8}, "Nested/oversized metadata array unsupported")
|
|
285
|
+
# Array values are preserved as raw bytes; do not build vocabulary views.
|
|
286
|
+
if subtype == 8:
|
|
287
|
+
for _ in range(count):
|
|
288
|
+
self.string()
|
|
289
|
+
else:
|
|
290
|
+
remaining = count * struct.calcsize("<" + scalar[subtype])
|
|
291
|
+
while remaining:
|
|
292
|
+
size = min(remaining, 65536)
|
|
293
|
+
self.read(size)
|
|
294
|
+
remaining -= size
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def verify_official(path, scanned, budget):
|
|
299
|
+
from gguf import GGUFReader
|
|
300
|
+
budget.check()
|
|
301
|
+
reader = GGUFReader(path, mode="r")
|
|
302
|
+
need(len(reader.tensors) == len(scanned.tensors) and reader.data_offset == scanned.dataStart, "Official GGUF reader directory differs")
|
|
303
|
+
for actual, expected in zip(reader.tensors, scanned.tensors):
|
|
304
|
+
need(actual.name == expected["name"] and list(map(int, actual.shape)) == expected["ne"] and actual.tensor_type.name == expected["qtype"] and actual.n_bytes == expected["sizeBytes"] and actual.data_offset == expected["dataOffset"], "Official GGUF geometry/type/payload extent differs")
|
|
305
|
+
del reader
|
|
306
|
+
budget.check()
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def verified_file(path, ref, budget, operand=False):
|
|
310
|
+
fields(ref, ("uri", "sha256", "sizeBytes"), ("mediaType",))
|
|
311
|
+
need(re.fullmatch("[a-f0-9]{64}", ref["sha256"]) and ref["uri"] == "omnius-artifact://sha256/" + ref["sha256"], "Bad full artifact identity")
|
|
312
|
+
integer(ref["sizeBytes"])
|
|
313
|
+
need(regular(path).st_size == ref["sizeBytes"], "Declared input file size changed")
|
|
314
|
+
seen = budget.artifactHashes if operand else budget.inputHashes
|
|
315
|
+
if ref["sha256"] not in seen:
|
|
316
|
+
need(ref["sizeBytes"] + (budget.artifacts if operand else budget.input) <= budget.limits["maxArtifactBytes" if operand else "maxInputBytes"], "Input/operand byte admission exceeded")
|
|
317
|
+
actual = hash_file(path, budget)
|
|
318
|
+
need(actual == {"sha256": ref["sha256"], "sizeBytes": ref["sizeBytes"]}, "Full source/operand artifact changed")
|
|
319
|
+
if ref["sha256"] not in seen:
|
|
320
|
+
if operand:
|
|
321
|
+
budget.artifacts += actual["sizeBytes"]
|
|
322
|
+
need(budget.artifacts <= budget.limits["maxArtifactBytes"], "Aggregate operand byte budget exceeded")
|
|
323
|
+
else:
|
|
324
|
+
budget.input += actual["sizeBytes"]
|
|
325
|
+
need(budget.input <= budget.limits["maxInputBytes"], "Aggregate parent checkpoint byte budget exceeded")
|
|
326
|
+
seen.add(ref["sha256"])
|
|
327
|
+
budget.verified[str(path)] = ref["sha256"]
|
|
328
|
+
return actual
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def logical_dtype(qtype):
|
|
332
|
+
return {"F32": "f32", "F16": "f16", "BF16": "bf16", "F64": "f64", "I8": "i8", "I16": "i16", "I32": "i32", "I64": "i64"}.get(qtype, "quantized")
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def dense_site(site, tensor):
|
|
336
|
+
need(site["kind"] == "parameter" and site["shape"] == tensor["shape"] and site["dtype"] == logical_dtype(tensor["qtype"]) and tensor["qtype"] in SUPPORTED, "Frozen parameter shape/storage type mismatch")
|
|
337
|
+
name, role, rank = site["name"], site["role"], len(site["shape"])
|
|
338
|
+
if name in ("token_embd.weight", "output.weight"):
|
|
339
|
+
need(rank == 2 and role in ("embedding", "other"), "Unverified dense output/embedding role")
|
|
340
|
+
elif re.fullmatch(r"blk\.\d+\.ffn_(up|gate|down)\.weight", name):
|
|
341
|
+
need(rank == 2 and role == "ffn", "Unverified dense FFN geometry")
|
|
342
|
+
elif re.fullmatch(r"blk\.\d+\.attn_(q|k|v|qkv|output)\.weight", name):
|
|
343
|
+
need(rank == 2 and role == "attention", "Unverified dense attention geometry")
|
|
344
|
+
elif name == "output_norm.weight" or re.fullmatch(r"blk\.\d+\.(attn_norm|ffn_norm|attn_q_norm|attn_k_norm)\.weight", name):
|
|
345
|
+
need(rank == 1 and role == "norm", "Unverified normalization parameter")
|
|
346
|
+
elif re.fullmatch(r"blk\.\d+\.(ffn_(up|gate|down)|attn_(q|k|v|qkv|output))\.bias", name):
|
|
347
|
+
need(rank == 1 and role == "bias", "Unverified dense bias geometry")
|
|
348
|
+
else:
|
|
349
|
+
raise ValueError("Unsupported/unverified dense GGUF parameter name; MoE/router semantics are not inferred")
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class Checkpoint:
|
|
353
|
+
def __init__(self, value, root, identity, budget):
|
|
354
|
+
fields(identity, ("modelJson", "tensorSitesJson"))
|
|
355
|
+
body = {k: v for k, v in value.items() if k not in ("id", "modelDigest")}
|
|
356
|
+
need(same(parse(identity["modelJson"]), body) and digest(identity["modelJson"].encode()) == value["modelDigest"], "Canonical full model identity mismatch")
|
|
357
|
+
need(same(parse(identity["tensorSitesJson"]), value["tensorSites"]) and digest(identity["tensorSitesJson"].encode()) == value["architectureMapDigest"], "Canonical tensor inventory identity mismatch")
|
|
358
|
+
need(value["format"] == "gguf", "Expected one single-file GGUF parent")
|
|
359
|
+
self.model, self.root, self.budget = value, root, budget
|
|
360
|
+
self.files = {}
|
|
361
|
+
for f in value["files"]:
|
|
362
|
+
path = safe(root, f["path"])
|
|
363
|
+
verified_file(path, f["artifact"], budget)
|
|
364
|
+
self.files[f["path"]] = path
|
|
365
|
+
weights = [f for f in value["files"] if f["role"] == "weights"]
|
|
366
|
+
need(len(weights) == 1, "Split/multiple GGUF weight files unsupported")
|
|
367
|
+
self.name = weights[0]["path"]
|
|
368
|
+
self.path = self.files[self.name]
|
|
369
|
+
self.scan = Scanner(self.path, budget)
|
|
370
|
+
self.sites = {s["id"]: s for s in value["tensorSites"]}
|
|
371
|
+
for site in value["tensorSites"]:
|
|
372
|
+
if site["kind"] == "parameter":
|
|
373
|
+
tensor = self.scan.byName.get(site["name"])
|
|
374
|
+
need(tensor is not None and tensor["shape"] == site["shape"] and logical_dtype(tensor["qtype"]) == site["dtype"], "Declared parameter does not match actual GGUF inventory")
|
|
375
|
+
|
|
376
|
+
def tensor(self, site):
|
|
377
|
+
import numpy as np
|
|
378
|
+
from gguf import quants, GGMLQuantizationType
|
|
379
|
+
tensor = self.scan.byName[site["name"]]
|
|
380
|
+
dense_site(site, tensor)
|
|
381
|
+
self.budget.reserve(tensor["elements"] * 128 + tensor["sizeBytes"] * 3)
|
|
382
|
+
with self.path.open("rb") as stream:
|
|
383
|
+
stream.seek(tensor["dataOffset"])
|
|
384
|
+
raw = stream.read(tensor["sizeBytes"])
|
|
385
|
+
need(len(raw) == tensor["sizeBytes"], "Truncated GGUF source tensor")
|
|
386
|
+
if tensor["qtype"] in ("F32", "F16"):
|
|
387
|
+
data = np.frombuffer(raw, dtype="<f4" if tensor["qtype"] == "F32" else "<f2").reshape(tensor["shape"]).astype(np.float64)
|
|
388
|
+
else:
|
|
389
|
+
qt = GGMLQuantizationType[tensor["qtype"]]
|
|
390
|
+
from gguf.quants import quant_shape_to_byte_shape
|
|
391
|
+
data = quants.dequantize(np.frombuffer(raw, dtype=np.uint8).reshape(quant_shape_to_byte_shape(tensor["shape"], qt)), qt).astype(np.float64)
|
|
392
|
+
need(bool(np.isfinite(data).all()), "Source tensor contains nonfinite decoded values")
|
|
393
|
+
return data
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
class Editor:
|
|
397
|
+
def __init__(self, payload, budget, sources):
|
|
398
|
+
self.payload, self.budget, self.sources = payload, budget, sources
|
|
399
|
+
self.operands = {}
|
|
400
|
+
# Validate every declared operand before any semantic-neutral fast path.
|
|
401
|
+
for op in payload["recipe"]["operations"]:
|
|
402
|
+
refs = []
|
|
403
|
+
if op["operation"] == "WEIGHT_ADD" and op["delta"]["kind"] == "tensor": refs.append(op["delta"]["tensor"])
|
|
404
|
+
if op["operation"] == "WEIGHT_GAIN" and op["gain"]["kind"] == "axis": refs.append(op["gain"]["factors"])
|
|
405
|
+
if op["operation"] == "WEIGHT_REPLACE": refs.append(op["replacement"])
|
|
406
|
+
if op["operation"] == "WEIGHT_PROJECT": refs.append(op["basis"])
|
|
407
|
+
if op["operation"] == "LOW_RANK_UPDATE": refs += [op["a"], op["b"]]
|
|
408
|
+
for ref in refs:
|
|
409
|
+
self.operand(ref)
|
|
410
|
+
|
|
411
|
+
def operand(self, ref):
|
|
412
|
+
import numpy as np
|
|
413
|
+
fields(ref, ("artifact", "shape", "dtype"))
|
|
414
|
+
shape, dtype, artifact = ref["shape"], ref["dtype"], ref["artifact"]
|
|
415
|
+
need(type(shape) is list and 1 <= len(shape) <= 4 and dtype in set(FLOATS) | {"bf16"}, "Unsupported floating operand shape/type")
|
|
416
|
+
n = math.prod(integer(x, 1) for x in shape)
|
|
417
|
+
integer(n, 1)
|
|
418
|
+
key = digest(encoded(ref))
|
|
419
|
+
if key in self.operands:
|
|
420
|
+
return self.operands[key]
|
|
421
|
+
path = safe(Path(self.payload["artifactRoot"]), artifact["sha256"][:2] + "/" + artifact["sha256"])
|
|
422
|
+
verified_file(path, artifact, self.budget, True)
|
|
423
|
+
self.budget.reserve(artifact["sizeBytes"] * 3 + n * 32)
|
|
424
|
+
raw = path.read_bytes()
|
|
425
|
+
if artifact.get("mediaType") == "application/json":
|
|
426
|
+
value = parse(raw)
|
|
427
|
+
fields(value, ("schema", "shape", "dtype", "data"))
|
|
428
|
+
need(value["schema"] == "omnius.nol.tensor.v1" and value["shape"] == shape and value["dtype"] == dtype and type(value["data"]) is list and len(value["data"]) == n, "Operand JSON descriptor mismatch")
|
|
429
|
+
data = np.array([finite(x) for x in value["data"]], dtype="<f4" if dtype == "bf16" else FLOATS[dtype])
|
|
430
|
+
if dtype == "bf16":
|
|
431
|
+
bits = data.view(np.uint32)
|
|
432
|
+
need(bool((bits & 65535 == 0).all()), "JSON BF16 operand is not exactly representable")
|
|
433
|
+
else:
|
|
434
|
+
width = 2 if dtype == "bf16" else np.dtype(FLOATS[dtype]).itemsize
|
|
435
|
+
need(len(raw) == n * width, "Binary operand byte length differs from descriptor")
|
|
436
|
+
data = ((np.frombuffer(raw, dtype="<u2").astype(np.uint32) << 16).view(np.float32) if dtype == "bf16" else np.frombuffer(raw, dtype=FLOATS[dtype]))
|
|
437
|
+
need(bool(np.isfinite(data).all()), "Nonfinite/overflowed operand")
|
|
438
|
+
result = data.reshape(shape).astype(np.float64)
|
|
439
|
+
self.operands[key] = result
|
|
440
|
+
return result
|
|
441
|
+
|
|
442
|
+
def apply(self, op, current, site, baseline_tensor):
|
|
443
|
+
import numpy as np
|
|
444
|
+
kind, shape, n = op["operation"], list(current.shape), current.size
|
|
445
|
+
self.lastIdentity = False
|
|
446
|
+
need(kind in OPS and op["tokenScope"] == {"kind": "all"}, "Only all-token static parameter edits are supported")
|
|
447
|
+
self.budget.reserve(n * 96)
|
|
448
|
+
if kind == "WEIGHT_ADD":
|
|
449
|
+
delta = op["delta"]
|
|
450
|
+
value = finite(delta["value"]) if delta["kind"] == "scalar" else self.operand(delta["tensor"])
|
|
451
|
+
need(isinstance(value, float) or list(value.shape) == shape, "Addition operand geometry mismatch")
|
|
452
|
+
self.budget.work(n)
|
|
453
|
+
if (isinstance(value, float) and value == 0) or (not isinstance(value, float) and bool((value == 0).all())):
|
|
454
|
+
self.lastIdentity = True; return current
|
|
455
|
+
result = np.where(value == 0, current, current + value)
|
|
456
|
+
elif kind == "WEIGHT_GAIN":
|
|
457
|
+
gain = op["gain"]
|
|
458
|
+
if gain["kind"] == "scalar":
|
|
459
|
+
value = finite(gain["factor"])
|
|
460
|
+
if value == 1: self.lastIdentity = True; return current
|
|
461
|
+
else:
|
|
462
|
+
axis = integer(gain["axis"])
|
|
463
|
+
need(axis < len(shape), "Axis gain outside parameter")
|
|
464
|
+
value = self.operand(gain["factors"])
|
|
465
|
+
need(list(value.shape) == [shape[axis]], "Axis gain vector geometry mismatch")
|
|
466
|
+
view = [1] * len(shape); view[axis] = shape[axis]; value = value.reshape(view)
|
|
467
|
+
if bool((value == 1).all()): self.lastIdentity = True; return current
|
|
468
|
+
self.budget.work(n)
|
|
469
|
+
result = np.where(value == 1, current, current * value)
|
|
470
|
+
elif kind == "WEIGHT_REPLACE":
|
|
471
|
+
expected = "f32" if site["dtype"] == "quantized" else site["dtype"]
|
|
472
|
+
need(op["replacement"]["dtype"] == expected, "Replacement must use the source parameter logical dtype")
|
|
473
|
+
result = self.operand(op["replacement"])
|
|
474
|
+
need(list(result.shape) == shape, "Replacement geometry mismatch")
|
|
475
|
+
self.lastIdentity = bool(np.array_equal(result.view(np.uint64), current.view(np.uint64)))
|
|
476
|
+
self.budget.work(n)
|
|
477
|
+
result = result.copy()
|
|
478
|
+
elif kind == "WEIGHT_PROJECT":
|
|
479
|
+
need(len(shape) == 2 and op["normalization"] == "orthonormal" and op["side"] in ("left", "right"), "Projection requires an explicit orthonormal row basis")
|
|
480
|
+
basis = self.operand(op["basis"])
|
|
481
|
+
if basis.ndim == 1: basis = basis.reshape(1, -1)
|
|
482
|
+
dimension = shape[0 if op["side"] == "left" else 1]
|
|
483
|
+
need(basis.ndim == 2 and basis.shape[1] == dimension and 0 < basis.shape[0] <= dimension, "Projection basis geometry mismatch")
|
|
484
|
+
rank = basis.shape[0]
|
|
485
|
+
self.budget.reserve(rank * rank * 32)
|
|
486
|
+
self.budget.work((2 * dimension + 1) * rank * rank)
|
|
487
|
+
need(float(np.max(np.abs(basis @ basis.T - np.eye(rank)))) <= self.payload["orthogonalityTolerance"], "Projection basis is not orthonormal")
|
|
488
|
+
strength = finite(op["strength"])
|
|
489
|
+
if strength == 0: self.lastIdentity = True; return current
|
|
490
|
+
self.budget.work(5 * n * rank)
|
|
491
|
+
projected = basis.T @ (basis @ current) if op["side"] == "left" else (current @ basis.T) @ basis
|
|
492
|
+
result = np.where(projected == 0, current, current - strength * projected)
|
|
493
|
+
elif kind == "LOW_RANK_UPDATE":
|
|
494
|
+
rank = integer(op["rank"], 1)
|
|
495
|
+
a, b = self.operand(op["a"]), self.operand(op["b"])
|
|
496
|
+
need(len(shape) == 2 and op["scaling"] == "alpha_over_rank" and list(a.shape) == [rank, shape[1]] and list(b.shape) == [shape[0], rank], "Low-rank A/B geometry/scaling mismatch")
|
|
497
|
+
factor = finite(finite(op["scale"]) * finite(op["alpha"]) / rank)
|
|
498
|
+
if finite(op["scale"]) == 0 or finite(op["alpha"]) == 0:
|
|
499
|
+
self.lastIdentity = True; return current
|
|
500
|
+
if factor == 0: return current
|
|
501
|
+
self.budget.work(2 * n * rank + 2 * n)
|
|
502
|
+
delta = b @ a
|
|
503
|
+
result = np.where(delta == 0, current, current + factor * delta)
|
|
504
|
+
else:
|
|
505
|
+
terms, seen = [], set()
|
|
506
|
+
for source in op["sources"]:
|
|
507
|
+
key = (source["modelDigest"], source["siteId"])
|
|
508
|
+
need(key not in seen and source["modelDigest"] in self.payload["recipe"]["parentModelDigests"], "Duplicate/undeclared merge source")
|
|
509
|
+
seen.add(key)
|
|
510
|
+
parent = self.sources.get(source["modelDigest"])
|
|
511
|
+
source_site = parent.sites.get(source["siteId"]) if parent else None
|
|
512
|
+
need(source_site and source_site["kind"] == "parameter" and source_site["name"] == site["name"] and source_site["shape"] == shape and source_site["dtype"] == site["dtype"], "Full merge parameter name/shape/dtype mismatch")
|
|
513
|
+
source_tensor = parent.scan.byName[source_site["name"]]
|
|
514
|
+
need(source_tensor["qtype"] == baseline_tensor["qtype"], "Merge source physical GGUF type differs")
|
|
515
|
+
weight = finite(source["weight"])
|
|
516
|
+
# Even zero-weight parents have already been full-hash verified.
|
|
517
|
+
value = parent.tensor(source_site)
|
|
518
|
+
if weight != 0: terms.append((value, weight))
|
|
519
|
+
self.budget.work(2 * n * len(terms))
|
|
520
|
+
if len(terms) == 1 and terms[0][1] == 1:
|
|
521
|
+
result = terms[0][0].copy()
|
|
522
|
+
self.lastIdentity = bool(np.array_equal(result.view(np.uint64), current.view(np.uint64)))
|
|
523
|
+
else:
|
|
524
|
+
result = np.zeros(shape, dtype=np.float64)
|
|
525
|
+
for value, weight in terms: result = result + weight * value
|
|
526
|
+
need(bool(np.isfinite(result).all()), "Nonfinite float64 operation result")
|
|
527
|
+
return result
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def l2(value):
|
|
531
|
+
import numpy as np
|
|
532
|
+
maximum = float(np.max(np.abs(value)))
|
|
533
|
+
if maximum == 0: return 0.0
|
|
534
|
+
result = maximum * math.sqrt(float(np.sum((value / maximum) ** 2, dtype=np.float64)))
|
|
535
|
+
need(math.isfinite(result), "Norm overflow beyond supported numeric range")
|
|
536
|
+
return result
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def independent_decode(raw, shape, target):
|
|
540
|
+
import numpy as np
|
|
541
|
+
if target == "F16":
|
|
542
|
+
return np.frombuffer(raw, dtype="<f2").astype(np.float64).reshape(shape)
|
|
543
|
+
# Independent Q8_0 wire decoder: one IEEE-f16 scale + 32 signed bytes.
|
|
544
|
+
need(shape[-1] % 32 == 0 and len(raw) == math.prod(shape) // 32 * 34, "Q8_0 encoded extent mismatch")
|
|
545
|
+
blocks = np.frombuffer(raw, dtype=np.dtype([("scale", "<f2"), ("values", "i1", (32,))]))
|
|
546
|
+
return (blocks["scale"].astype(np.float64)[:, None] * blocks["values"].astype(np.float64)).reshape(shape)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def encode_tensor(value, policy, budget):
|
|
550
|
+
import numpy as np
|
|
551
|
+
from gguf import quants, GGMLQuantizationType
|
|
552
|
+
target = "F16" if policy["target"] == "f16" else "Q8_0"
|
|
553
|
+
budget.work(value.size * 8)
|
|
554
|
+
if target == "F16":
|
|
555
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
556
|
+
raw = np.ascontiguousarray(value, dtype="<f2").tobytes()
|
|
557
|
+
else:
|
|
558
|
+
need(value.ndim == 2 and value.shape[-1] % 32 == 0, "Q8_0 output requires a 2D dense matrix with block-aligned logical last axis")
|
|
559
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
560
|
+
f32 = value.astype(np.float32)
|
|
561
|
+
need(bool(np.isfinite(f32).all()), "Q8_0 float32 staging overflow")
|
|
562
|
+
raw = quants.quantize(f32, GGMLQuantizationType.Q8_0).tobytes()
|
|
563
|
+
decoded = independent_decode(raw, value.shape, target)
|
|
564
|
+
need(bool(np.isfinite(decoded).all()), "Storage dtype overflow/nonfinite round trip")
|
|
565
|
+
error = decoded - value
|
|
566
|
+
absolute = float(np.max(np.abs(error)))
|
|
567
|
+
relative = l2(error) / max(l2(value), sys.float_info.min)
|
|
568
|
+
need(math.isfinite(relative) and absolute <= policy["maxAbsError"] and relative <= policy["maxRelativeL2Error"], "Actual storage round-trip error exceeds declared bounds")
|
|
569
|
+
return raw, target, {"maxAbsError": absolute, "relativeL2Error": relative, "changedReferenceElements": int(np.count_nonzero(decoded.view(np.uint64) != value.view(np.uint64)))}
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def copy_range(source, destination, start, size, budget):
|
|
573
|
+
source.seek(start)
|
|
574
|
+
while size:
|
|
575
|
+
budget.check()
|
|
576
|
+
block = source.read(min(size, 65536))
|
|
577
|
+
need(block, "Source truncated during stream copy")
|
|
578
|
+
destination.write(block)
|
|
579
|
+
size -= len(block)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def admit_output(stage, additional, budget):
|
|
583
|
+
# Includes private tensor temporaries, not just the final exported files.
|
|
584
|
+
used = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file())
|
|
585
|
+
need(used + additional <= budget.limits["maxOutputBytes"], "Staged output high-water byte budget exceeded")
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def write_gguf(base, changes, output, budget):
|
|
589
|
+
scan = base.scan
|
|
590
|
+
admit_output(output.parent, scan.size + sum(c["sizeBytes"] for c in changes.values()) + (scan.alignment * len(scan.tensors) if changes else 0), budget)
|
|
591
|
+
with base.path.open("rb") as source, output.open("xb") as dest:
|
|
592
|
+
if not changes:
|
|
593
|
+
copy_range(source, dest, 0, scan.size, budget)
|
|
594
|
+
else:
|
|
595
|
+
# Preserve the complete raw metadata/header/directory representation;
|
|
596
|
+
# only the exact qtype and relative-offset fields may be rewritten.
|
|
597
|
+
prefix = bytearray(source.read(scan.dataStart))
|
|
598
|
+
dest.write(prefix)
|
|
599
|
+
oldEnd = scan.dataStart
|
|
600
|
+
for tensor in sorted(scan.tensors, key=lambda t: t["dataOffset"]):
|
|
601
|
+
copy_range(source, dest, oldEnd, tensor["dataOffset"] - oldEnd, budget)
|
|
602
|
+
padding = (-(dest.tell() - scan.dataStart)) % scan.alignment
|
|
603
|
+
dest.write(b"\0" * padding)
|
|
604
|
+
relative = dest.tell() - scan.dataStart
|
|
605
|
+
replacement = changes.get(tensor["name"])
|
|
606
|
+
if replacement:
|
|
607
|
+
with Path(replacement["path"]).open("rb") as rewritten:
|
|
608
|
+
copy_range(rewritten, dest, 0, replacement["sizeBytes"], budget)
|
|
609
|
+
struct.pack_into("<I", prefix, tensor["typeOffset"], replacement["typeId"])
|
|
610
|
+
else:
|
|
611
|
+
copy_range(source, dest, tensor["dataOffset"], tensor["sizeBytes"], budget)
|
|
612
|
+
struct.pack_into("<Q", prefix, tensor["offsetField"], relative)
|
|
613
|
+
oldEnd = tensor["dataOffset"] + tensor["sizeBytes"]
|
|
614
|
+
copy_range(source, dest, oldEnd, scan.size - oldEnd, budget)
|
|
615
|
+
need(dest.tell() <= budget.limits["maxOutputBytes"], "Actual output byte budget exceeded")
|
|
616
|
+
dest.seek(0); dest.write(prefix)
|
|
617
|
+
dest.flush(); os.fsync(dest.fileno())
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def edit(payload):
|
|
621
|
+
import numpy as np
|
|
622
|
+
from gguf import GGMLQuantizationType
|
|
623
|
+
fields(payload, ("model", "recipe", "recipeJson", "identity", "sourceCheckpoints", "checkpointRoot", "artifactRoot", "stageDirectory", "outputName", "exportId", "limits", "orthogonalityTolerance", "encoding", "runtime", "dependencyLockPath"))
|
|
624
|
+
budget = Budget(payload["limits"])
|
|
625
|
+
actualRuntime = runtime_inventory(payload["dependencyLockPath"])
|
|
626
|
+
need(same(actualRuntime, payload["runtime"]), "Pinned full GGUF/NumPy/runtime dependency inventory changed")
|
|
627
|
+
policy = payload["encoding"]
|
|
628
|
+
fields(policy, ("target", "maxAbsError", "maxRelativeL2Error"))
|
|
629
|
+
need(policy["target"] in ("f16", "q8_0") and finite(policy["maxAbsError"]) >= 0 and finite(policy["maxRelativeL2Error"]) >= 0, "Explicit finite output quantization/error policy required")
|
|
630
|
+
need(0 < finite(payload["orthogonalityTolerance"]) <= 0.01, "Invalid orthogonality tolerance")
|
|
631
|
+
recipe = payload["recipe"]
|
|
632
|
+
recipeBody = {k: v for k, v in recipe.items() if k != "recipeDigest"}
|
|
633
|
+
need(same(parse(payload["recipeJson"]), recipeBody) and digest(payload["recipeJson"].encode()) == recipe["recipeDigest"], "Full canonical recipe identity mismatch")
|
|
634
|
+
need(recipe["calibrations"] == [] and 0 < len(recipe["operations"]) <= budget.limits["maxOperations"] and all(o["operation"] in OPS and o["tokenScope"] == {"kind": "all"} for o in recipe["operations"]), "Unsupported recipe operations/calibrations/scope")
|
|
635
|
+
stage = Path(payload["stageDirectory"])
|
|
636
|
+
need(stage.is_dir() and not stage.is_symlink() and not list(stage.iterdir()), "Private empty stage required")
|
|
637
|
+
base = Checkpoint(payload["model"], Path(payload["checkpointRoot"]), payload["identity"], budget)
|
|
638
|
+
need(recipe["modelDigest"] == base.model["modelDigest"] and recipe["architectureMapDigest"] == base.model["architectureMapDigest"], "Recipe/base parameter identity mismatch")
|
|
639
|
+
sources = {base.model["modelDigest"]: base}
|
|
640
|
+
for source in payload["sourceCheckpoints"]:
|
|
641
|
+
fields(source, ("model", "root", "identity"))
|
|
642
|
+
parent = Checkpoint(source["model"], Path(source["root"]), source["identity"], budget)
|
|
643
|
+
key = parent.model["modelDigest"]
|
|
644
|
+
need(key in recipe["parentModelDigests"] and key not in sources, "Duplicate/undeclared full merge parent")
|
|
645
|
+
sources[key] = parent
|
|
646
|
+
need(set(sources) == set(recipe["parentModelDigests"]), "Every declared parent must be completely supplied and verified")
|
|
647
|
+
editor = Editor(payload, budget, sources)
|
|
648
|
+
grouped = {}
|
|
649
|
+
for op in recipe["operations"]:
|
|
650
|
+
site = base.sites.get(op["siteId"])
|
|
651
|
+
need(site and site["kind"] == "parameter", "Unknown static parameter target")
|
|
652
|
+
tensor = base.scan.byName.get(site["name"])
|
|
653
|
+
need(tensor is not None, "Missing actual target tensor")
|
|
654
|
+
dense_site(site, tensor)
|
|
655
|
+
grouped.setdefault(site["name"], (site, []))[1].append(op)
|
|
656
|
+
changes, operations, final = {}, [], []
|
|
657
|
+
for name, (site, ops) in grouped.items():
|
|
658
|
+
tensor = base.scan.byName[name]
|
|
659
|
+
original = base.tensor(site)
|
|
660
|
+
value = original
|
|
661
|
+
explicitIdentity = True
|
|
662
|
+
for op in ops:
|
|
663
|
+
before = value
|
|
664
|
+
value = editor.apply(op, value, site, tensor)
|
|
665
|
+
explicitIdentity = explicitIdentity and editor.lastIdentity
|
|
666
|
+
changed = int(np.count_nonzero(value.view(np.uint64) != before.view(np.uint64)))
|
|
667
|
+
operations.append({"operationId": op["id"], "operation": op["operation"], "siteId": op["siteId"], "name": name, "changedReferenceElements": changed, "operatorOrder": next(i for i, declared in enumerate(recipe["operations"]) if declared["id"] == op["id"]), "evaluationOrder": len(operations), "beforeReferenceSha256": digest(before.astype("<f8", copy=False).tobytes()), "afterReferenceSha256": digest(value.astype("<f8", copy=False).tobytes()), "referencePrecision": "float64", "storageEncodePerformed": False})
|
|
668
|
+
neutral = explicitIdentity and bool(np.array_equal(value.view(np.uint64), original.view(np.uint64)))
|
|
669
|
+
beforeHash = range_hash(base.path, tensor["dataOffset"], tensor["sizeBytes"], budget)
|
|
670
|
+
if neutral:
|
|
671
|
+
final.append({"name": name, "from": tensor["qtype"], "to": tensor["qtype"], "neutral": True, "beforeTensorSha256": beforeHash, "afterTensorSha256": beforeHash, "maxAbsError": 0.0, "relativeL2Error": 0.0})
|
|
672
|
+
else:
|
|
673
|
+
raw, target, error = encode_tensor(value, policy, budget)
|
|
674
|
+
path = stage / (".tensor-" + str(len(changes)))
|
|
675
|
+
admit_output(stage, len(raw), budget)
|
|
676
|
+
with path.open("xb") as stream:
|
|
677
|
+
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
|
|
678
|
+
changes[name] = {"path": str(path), "typeId": int(GGMLQuantizationType[target]), "sizeBytes": len(raw)}
|
|
679
|
+
final.append({"name": name, "from": tensor["qtype"], "to": target, "neutral": False, "beforeTensorSha256": beforeHash, "afterTensorSha256": digest(raw), **error})
|
|
680
|
+
output = stage / payload["outputName"]
|
|
681
|
+
need(output.parent == stage and output.name not in ("", ".", "..") and not output.name.startswith("."), "Unsafe output GGUF filename")
|
|
682
|
+
write_gguf(base, changes, output, budget)
|
|
683
|
+
check = Scanner(output, budget)
|
|
684
|
+
need(range_hash(base.path, 24, base.scan.metadataEnd - 24, budget) == range_hash(output, 24, check.metadataEnd - 24, budget), "Raw metadata representation changed")
|
|
685
|
+
need([t["name"] for t in check.tensors] == [t["name"] for t in base.scan.tensors], "Tensor inventory order changed")
|
|
686
|
+
unchanged = []
|
|
687
|
+
for tensor in base.scan.tensors:
|
|
688
|
+
actual = check.byName[tensor["name"]]
|
|
689
|
+
need(actual["shape"] == tensor["shape"], "Exported logical geometry changed")
|
|
690
|
+
expected = next((item for item in final if item["name"] == tensor["name"]), None)
|
|
691
|
+
if tensor["name"] not in changes:
|
|
692
|
+
need(actual["qtype"] == tensor["qtype"] and range_hash(base.path, tensor["dataOffset"], tensor["sizeBytes"], budget) == range_hash(output, actual["dataOffset"], actual["sizeBytes"], budget), "Untouched tensor bytes/storage type changed")
|
|
693
|
+
unchanged.append({"name": tensor["name"], "sha256": range_hash(output, actual["dataOffset"], actual["sizeBytes"], budget)})
|
|
694
|
+
else:
|
|
695
|
+
need(actual["qtype"] == expected["to"] and range_hash(output, actual["dataOffset"], actual["sizeBytes"], budget) == expected["afterTensorSha256"], "Stored edited tensor differs from independently checked encoding")
|
|
696
|
+
verify_official(output, check, budget)
|
|
697
|
+
for item in changes.values(): Path(item["path"]).unlink()
|
|
698
|
+
files = []
|
|
699
|
+
for f in base.model["files"]:
|
|
700
|
+
source = base.files[f["path"]]
|
|
701
|
+
if f["role"] == "weights": destination = output
|
|
702
|
+
else:
|
|
703
|
+
destination = stage / f["path"]
|
|
704
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
705
|
+
admit_output(stage, regular(source).st_size, budget)
|
|
706
|
+
with source.open("rb") as s, destination.open("xb") as d:
|
|
707
|
+
copy_range(s, d, 0, regular(source).st_size, budget); d.flush(); os.fsync(d.fileno())
|
|
708
|
+
files.append({"path": payload["outputName"] if f["role"] == "weights" else f["path"], "role": f["role"], "before": hash_file(source, budget), "after": hash_file(destination, budget)})
|
|
709
|
+
# Recheck all declared parents and operands after math/copy and before commit.
|
|
710
|
+
for parent in sources.values():
|
|
711
|
+
for f in parent.model["files"]: verified_file(parent.files[f["path"]], f["artifact"], budget)
|
|
712
|
+
for path, ref in list(budget.verified.items()):
|
|
713
|
+
need(hash_file(Path(path), budget)["sha256"] == ref, "Declared input changed before publication")
|
|
714
|
+
runtimePath = ".omnius-nol-gguf-runtime." + payload["exportId"] + ".json"
|
|
715
|
+
runtimeFile = stage / runtimePath
|
|
716
|
+
runtimeRaw = encoded(actualRuntime)
|
|
717
|
+
admit_output(stage, len(runtimeRaw), budget)
|
|
718
|
+
runtimeFile.write_bytes(runtimeRaw)
|
|
719
|
+
with runtimeFile.open("rb") as stream: os.fsync(stream.fileno())
|
|
720
|
+
runtimeInfo = hash_file(runtimeFile, budget)
|
|
721
|
+
runtimeArtifact = {**runtimeInfo, "uri": "omnius-artifact://sha256/" + runtimeInfo["sha256"], "mediaType": "application/json"}
|
|
722
|
+
operations.sort(key=lambda op: op["operatorOrder"])
|
|
723
|
+
result = {"schema": "omnius.nol.gguf-checkpoint-edit.v1", "exportId": payload["exportId"], "editorSha256": hash_file(Path(__file__).resolve(strict=True), budget)["sha256"], "runtimePath": runtimePath, "runtimeArtifact": runtimeArtifact, "parentModelDigest": base.model["modelDigest"], "recipeDigest": recipe["recipeDigest"], "sourceModelDigests": sorted(sources), "runtimeDigest": actualRuntime["runtimeDigest"], "numericalPolicy": "declared_operator_order_float64_reference_then_one_final_storage_encode_per_changed_tensor; no_per_operation_storage_rounding; native_blas_reassociation_possible", "equivalence": "approximate_transfer_needs_native_validation", "neutralPolicy": "explicit_zero_add_unit_gain_zero_projection_or_scale_bitwise_identity_replace_merge_only_preserves_original_bytes", "allNeutral": not changes, "encoding": policy, "operations": operations, "tensors": final, "unchangedTensors": unchanged, "metadataSha256": range_hash(output, 24, check.metadataEnd - 24, budget), "officialReaderVerified": True, "files": files, "inferencePerformed": False, "cudaUsed": False, "nativeRuntimeImported": False, "usage": {"inputBytes": budget.input, "artifactBytes": budget.artifacts, "reservedWorkingBytes": budget.working, "arithmeticUnits": budget.arithmetic, "durationMs": int((time.monotonic() - budget.started) * 1000)}}
|
|
724
|
+
receipt = stage / (".omnius-nol-gguf-edit." + payload["exportId"] + ".json")
|
|
725
|
+
result["usage"]["outputBytes"] = 0
|
|
726
|
+
otherBytes = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file())
|
|
727
|
+
for _ in range(8):
|
|
728
|
+
size = otherBytes + len(encoded(result))
|
|
729
|
+
if result["usage"]["outputBytes"] == size: break
|
|
730
|
+
result["usage"]["outputBytes"] = size
|
|
731
|
+
admit_output(stage, len(encoded(result)), budget)
|
|
732
|
+
receipt.write_bytes(encoded(result))
|
|
733
|
+
with receipt.open("rb") as stream: os.fsync(stream.fileno())
|
|
734
|
+
size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file())
|
|
735
|
+
need(size <= budget.limits["maxOutputBytes"], "Complete export/receipt output budget exceeded")
|
|
736
|
+
need(result["usage"]["outputBytes"] == size, "Receipt/output byte accounting did not converge")
|
|
737
|
+
need(not any(n.startswith(("torch", "llama_cpp", "gne.runtime")) for n in sys.modules), "Native runtime unexpectedly imported")
|
|
738
|
+
return {"receipt": result, "receiptPath": receipt.name, "receiptArtifact": hash_file(receipt, budget)}
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def publish(payload):
|
|
742
|
+
fields(payload, ("stageDirectory", "outputDirectory", "exportId", "receiptSha256", "receiptPath"))
|
|
743
|
+
need(sys.platform.startswith("linux"), "Atomic no-replace publication requires Linux")
|
|
744
|
+
stage, target = Path(payload["stageDirectory"]), Path(payload["outputDirectory"])
|
|
745
|
+
need(stage.is_dir() and not stage.is_symlink() and stage.parent.resolve(strict=True) == target.parent.resolve(strict=True), "Publish stage/parent mismatch")
|
|
746
|
+
need(payload["receiptPath"] == ".omnius-nol-gguf-edit." + payload["exportId"] + ".json", "Publish receipt identity mismatch")
|
|
747
|
+
receipt = safe(stage, payload["receiptPath"])
|
|
748
|
+
need(hash_file(receipt)["sha256"] == payload["receiptSha256"] and parse(receipt.read_bytes())["exportId"] == payload["exportId"], "Publish receipt content changed")
|
|
749
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
750
|
+
rename = getattr(libc, "renameat2", None)
|
|
751
|
+
need(rename is not None, "No atomic no-replace rename support")
|
|
752
|
+
rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]; rename.restype = ctypes.c_int
|
|
753
|
+
if rename(-100, os.fsencode(stage), -100, os.fsencode(target), 1) != 0:
|
|
754
|
+
code = ctypes.get_errno(); raise OSError(code, os.strerror(code))
|
|
755
|
+
fd = os.open(target.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
|
|
756
|
+
try: os.fsync(fd)
|
|
757
|
+
finally: os.close(fd)
|
|
758
|
+
return {"published": True, "exportId": payload["exportId"]}
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
if __name__ == "__main__":
|
|
762
|
+
try:
|
|
763
|
+
signal.signal(signal.SIGTERM, lambda *_: (_ for _ in ()).throw(InterruptedError("GGUF editor cancelled")))
|
|
764
|
+
raw = sys.stdin.buffer.read(MAX_FRAME + 1)
|
|
765
|
+
need(len(raw) <= MAX_FRAME, "Absolute protocol bound exceeded")
|
|
766
|
+
payload = parse(raw)
|
|
767
|
+
if sys.argv[1:] == ["--inspect-runtime"]:
|
|
768
|
+
fields(payload, ("dependencyLockPath",)); result = runtime_inventory(payload["dependencyLockPath"])
|
|
769
|
+
elif sys.argv[1:] == ["--inspect"]:
|
|
770
|
+
fields(payload, ("checkpointPath", "limits", "runtime", "dependencyLockPath")); budget = Budget(payload["limits"])
|
|
771
|
+
actualRuntime = runtime_inventory(payload["dependencyLockPath"])
|
|
772
|
+
need(same(actualRuntime, payload["runtime"]), "Pinned GGUF inventory runtime changed")
|
|
773
|
+
checkpoint = Path(payload["checkpointPath"])
|
|
774
|
+
need(regular(checkpoint).st_size <= budget.limits["maxInputBytes"], "Checkpoint byte admission exceeded")
|
|
775
|
+
info = hash_file(checkpoint, budget); need(info["sizeBytes"] <= budget.limits["maxInputBytes"], "Checkpoint input bound exceeded")
|
|
776
|
+
scanned = Scanner(checkpoint, budget); verify_official(checkpoint, scanned, budget)
|
|
777
|
+
result = {"schema": "omnius.nol.gguf-inventory.v1", "runtimeDigest": actualRuntime["runtimeDigest"], "checkpoint": info, "version": scanned.version, "alignment": scanned.alignment, "metadataSha256": range_hash(checkpoint, 24, scanned.metadataEnd - 24, budget), "tensors": [{k: t[k] for k in ("name", "shape", "qtype", "sizeBytes", "dataOffset")} for t in scanned.tensors], "officialReaderVerified": True, "modelLoaded": False, "cudaUsed": False}
|
|
778
|
+
elif sys.argv[1:] == ["--publish"]: result = publish(payload)
|
|
779
|
+
else:
|
|
780
|
+
need(not sys.argv[1:], "Unknown GGUF editor action"); result = edit(payload)
|
|
781
|
+
output = encoded(result); need(len(output) <= MAX_FRAME, "Output protocol frame bound exceeded")
|
|
782
|
+
sys.stdout.buffer.write(output); sys.stdout.flush()
|
|
783
|
+
except BaseException as error:
|
|
784
|
+
sys.stderr.write((type(error).__name__ + ": " + str(error))[-4000:] + "; nativeRuntimeImported=" + str(any(n.startswith(("torch", "llama_cpp", "gne.runtime")) for n in sys.modules)).lower() + "\n")
|
|
785
|
+
sys.exit(1)
|