RLCD-27B / inference.py
SourceHat's picture
Release SourceHat RLCD 1.0.0 BF16
e7ed103
Raw History Blame Contribute Delete
22.9 kB
#!/usr/bin/env python3
"""Standalone dense-merged RLCD inference. No adapters or private imports."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import importlib.util
import json
import math
import os
from pathlib import Path
import re
import sys
from typing import Any
BASE_MODEL = "Cloudflare/clef"
BASE_REVISION = "0b331204bb13fbd2ca93a64df1956f5b55478ce5"
SCHEMA_VERSION = "typed-decision-v1"
MAX_LENGTH = 2048
MAX_FIELDS = 4
MAX_CANDIDATES = 16
MAX_REQUEST_BYTES = 1_048_576
MAX_TOTAL_TEXT = 32768
TYPE_NAMES = {"enum": "choice", "boolean": "noul", "ordinal": "score"}
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def _pairs(pairs):
value = {}
for key, item in pairs:
if key in value:
raise ValueError("duplicate JSON object key")
value[key] = item
return value
def read_json(path: Path, *, limit=MAX_REQUEST_BYTES):
if path.is_symlink() or not path.is_file() or path.stat().st_size > limit:
raise ValueError("expected a regular JSON file within the documented size limit")
return json.loads(path.read_text(), object_pairs_hook=_pairs,
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("nonfinite JSON number")))
def _keys(value, required, optional=()):
if not isinstance(value, dict) or not set(required) <= value.keys() or set(value) - set(required) - set(optional):
raise ValueError("object keys do not match the decision contract")
def _text(value, *, maximum=16384, empty=False):
if (not isinstance(value, str) or len(value) > maximum or (not empty and not value.strip())
or re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", value)
or re.search(r"<\|[^\n]*?\|>", value)):
raise ValueError("invalid text, control character, or model special token")
return value
@dataclass
class PreparedRequest:
native: dict[str, Any]
fields: list[dict[str, Any]]
candidate_ids: dict[str, list[str]]
canonical_fields: dict[str, str]
def prepare_request(request: dict[str, Any]) -> PreparedRequest:
_keys(request, ("state", "schema"))
state, schema = request["state"], request["schema"]
_keys(state, ("context",), ("evidence",))
context = _text(state["context"], empty=True)
evidence = state.get("evidence", [])
if not isinstance(evidence, list) or len(evidence) > 32:
raise ValueError("evidence must contain at most 32 text items")
evidence = [_text(item, maximum=4096) for item in evidence]
_keys(schema, ("version", "fields"), ("dependencies", "constraints"))
if schema["version"] != SCHEMA_VERSION:
raise ValueError("unsupported schema version")
fields = schema["fields"]
if not isinstance(fields, list) or not 1 <= len(fields) <= MAX_FIELDS:
raise ValueError("supply one to four fields")
descriptions, identifiers, checked = set(), set(), []
text_size = len(context) + sum(map(len, evidence))
for field in fields:
_keys(field, ("id", "field_type", "description", "candidates"), ("required",))
fid = _text(field["id"], maximum=128)
kind = field["field_type"]
description = _text(field["description"])
if fid in identifiers or kind not in TYPE_NAMES or (description, kind) in descriptions:
raise ValueError("field IDs and semantic descriptions must be distinct; field type is invalid")
if field.get("required", True) is not True:
raise ValueError("all released fields are required")
identifiers.add(fid)
descriptions.add((description, kind))
candidates = field["candidates"]
limit = 14 if kind == "ordinal" else MAX_CANDIDATES
if not isinstance(candidates, list) or not 2 <= len(candidates) <= limit or kind == "boolean" and len(candidates) != 2:
raise ValueError("candidate count is outside the released envelope")
ids, meanings, values = set(), set(), []
for candidate in candidates:
_keys(candidate, ("id", "description"))
cid = _text(candidate["id"], maximum=128)
meaning = _text(candidate["description"], maximum=2048)
if cid in ids or meaning in meanings:
raise ValueError("candidate IDs and descriptions must be distinct within a field")
ids.add(cid)
meanings.add(meaning)
values.append({"id": cid, "description": meaning})
text_size += len(meaning)
text_size += len(description)
checked.append({"id": fid, "field_type": kind, "description": description, "candidates": values})
dependencies = schema.get("dependencies", [])
constraints = schema.get("constraints", [])
if not isinstance(dependencies, list) or len(dependencies) > 16 or not isinstance(constraints, list) or len(constraints) > 16:
raise ValueError("too many dependencies or constraints")
dependencies = [dict(item) if isinstance(item, dict) else item for item in dependencies]
for dependency in dependencies:
_keys(dependency, ("source_field", "target_field", "description"))
if dependency["source_field"] not in identifiers or dependency["target_field"] not in identifiers:
raise ValueError("dependency refers to an unknown field")
text_size += len(_text(dependency["description"], maximum=4096))
constraints = [_text(item, maximum=4096) for item in constraints]
text_size += sum(map(len, constraints))
if text_size > MAX_TOTAL_TEXT:
raise ValueError("aggregate request text exceeds 32768 characters")
checked.sort(key=lambda field: (field["description"], field["field_type"]))
field_ids = {field["id"]: f"f{i:03d}" for i, field in enumerate(checked)}
dependencies.sort(key=lambda item: (field_ids[item["source_field"]], field_ids[item["target_field"]], item["description"]))
native_questions, candidate_ids = {}, {}
for field in checked:
fid, kind = field["id"], field["field_type"]
candidates = sorted(field["candidates"], key=lambda c: c["description"]) if kind == "enum" else field["candidates"]
candidate_ids[fid] = [candidate["id"] for candidate in candidates]
criteria: Any = {f"c{i:03d}": candidate["description"] for i, candidate in enumerate(candidates)}
if kind == "ordinal":
criteria = [candidate["description"] for candidate in candidates]
elif kind == "boolean":
criteria = dict(zip(("true", "false"), (candidate["description"] for candidate in candidates)))
instructions = field["description"]
related = [item["description"] for item in dependencies if fid in (item["source_field"], item["target_field"])]
if related:
instructions += " Dependencies: " + " ".join(related)
if constraints:
instructions += " Constraints: " + " ".join(constraints)
native_questions[field_ids[fid]] = {"type": TYPE_NAMES[kind], "instructions": instructions, "criteria": criteria}
return PreparedRequest({"state": {"context": context, "evidence": evidence}, "questions": native_questions},
checked, candidate_ids, field_ids)
def compile_request(runtime, tokenizer, prepared: PreparedRequest):
encoded = runtime.encode_record(tokenizer, prepared.native, max_length=10_000_000)
if len(encoded.input_ids) > MAX_LENGTH:
raise ValueError(f"compiled input contains {len(encoded.input_ids)} tokens; limit is {MAX_LENGTH}; truncation is forbidden")
if encoded.media is not None:
raise ValueError("the released interface is text-only")
return encoded
def verify_bundle(bundle: Path, *, strict=False):
bundle = bundle.resolve(strict=True)
manifest = read_json(bundle / "release_manifest.json", limit=4 * MAX_REQUEST_BYTES)
if (manifest.get("format") != "sourcehat-rlcd-release-v1" or manifest.get("base_model") != BASE_MODEL
or manifest.get("base_revision") != BASE_REVISION):
raise ValueError("release manifest does not match this loader")
files = manifest.get("files", {})
if not files or len(files) > 40:
raise ValueError("invalid release file inventory")
actual = {str(path.relative_to(bundle)) for path in bundle.rglob("*") if path.is_file()}
if strict and actual != set(files) | {"release_manifest.json"}:
raise ValueError("release has missing or unexpected files")
for name, entry in files.items():
relative = Path(name)
if relative.is_absolute() or ".." in relative.parts:
raise ValueError("invalid manifest file path")
path = bundle / relative
if (any((bundle / Path(*relative.parts[:i])).is_symlink() for i in range(1, len(relative.parts) + 1))
or not path.is_file() or path.stat().st_size != entry["bytes"] or sha256_file(path) != entry["sha256"]):
raise ValueError("release file hash or regular-file check failed")
return manifest
def _runtime(bundle):
path = bundle / "clef_runtime.py"
name = "sourcehat_rlcd_runtime_" + sha256_file(path)[:16]
if name not in sys.modules:
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return sys.modules[name]
class DecisionModel:
def __init__(self, bundle=None, *, base_model_path=None, local_files_only=False, device="cuda:0"):
sys.dont_write_bytecode = True
self.bundle = Path(bundle or Path(__file__).resolve().parent).resolve(strict=True)
self.manifest = verify_bundle(self.bundle)
self.int8 = self.manifest.get("artifact_kind") == "int8_typed_decision_model"
config = read_json(self.bundle / "config.json")
if (self.manifest.get("artifact_kind") not in {"merged_typed_decision_model", "int8_typed_decision_model"}
or config.get("adapter_merged") is not True or self.manifest.get("base_files")
or any(k in config for k in ("text_adaptation", "adaptation_dtype", "adapter_dtype"))):
raise ValueError("this loader requires a fully dense-merged, self-contained model")
if base_model_path is not None:
raise ValueError("do not supply a separate base model")
self.merged = True
self.base_path = self.bundle
self.device = device
self.local_files_only = local_files_only
self.model = None
self.runtime = _runtime(self.bundle)
from transformers import AutoTokenizer
self.tokenizer = AutoTokenizer.from_pretrained(self.base_path, local_files_only=True, trust_remote_code=False)
def compile(self, request):
prepared = prepare_request(request)
return prepared, compile_request(self.runtime, self.tokenizer, prepared)
def load(self):
if self.model is not None:
return
import torch
from transformers import Qwen3_5Config, Qwen3_5ForConditionalGeneration
visible = os.environ.get("CUDA_VISIBLE_DEVICES", "")
if not visible or len(visible.split(",")) != 1 or self.device != "cuda:0" or torch.cuda.device_count() != 1:
raise ValueError("select exactly one physical GPU using CUDA_VISIBLE_DEVICES and use cuda:0")
int8 = getattr(self, "int8", False)
total_memory = torch.cuda.get_device_properties(0).total_memory
minimum_gib = 32 if int8 else 60
if total_memory < minimum_gib * 2**30:
raise ValueError(f"this runtime requires a GPU with at least {minimum_gib} GiB VRAM; see measured requirements in README")
memory_ceiling = min(total_memory - 2 * 2**30, 40 * 2**30) if int8 else 60 * 2**30
torch.cuda.set_per_process_memory_fraction(memory_ceiling / total_memory, 0)
torch.set_num_threads(4)
config = read_json(self.bundle / "joint_head_config.json")
expected_config = {"hidden_size": 5120, "width": 1024, "routing_layers": 2,
"layers": 4, "heads": 16, "feedforward": 4096}
if config != expected_config:
raise ValueError("joint-head architecture differs from this release")
class SelectedFloatRows:
def __init__(self, values):
self.values = values
def __getitem__(self, indices):
return self.values[indices].float()
class FloatBoundary(torch.nn.Module):
def __init__(self, inner):
super().__init__()
self.inner = inner
def forward(self, hidden, ids, mask, records, output_weights):
return self.inner(hidden.float(), ids, mask, records, SelectedFloatRows(output_weights))
if self.merged:
from accelerate import init_empty_weights, load_checkpoint_and_dispatch
backbone_config = Qwen3_5Config.from_dict(read_json(self.bundle / "backbone_config.json"))
backbone_config.use_cache = False
backbone_config._attn_implementation = "sdpa"
with init_empty_weights():
backbone = Qwen3_5ForConditionalGeneration(backbone_config)
# RoPE buffers are initialized in FP32 and must not be rounded by a blanket model.to(dtype).
for parameter in backbone.parameters():
parameter.data = parameter.data.to(dtype=torch.bfloat16)
if int8:
install_int8_layers(backbone, self.bundle)
head = self.runtime.JointSchemaHead(**config).float()
model = self.runtime.ClefModel(backbone, FloatBoundary(head))
if int8:
from safetensors import safe_open
quantization = read_json(self.bundle / "quantization_config.json")
expected_keys = set(model.state_dict()) | {name + ".SCB" for name in quantization["modules"]}
with safe_open(self.bundle / "model.safetensors", framework="pt", device="cpu") as weights:
if set(weights.keys()) != expected_keys:
raise ValueError("INT8 checkpoint inventory differs from the complete model architecture")
if int8:
self.model = load_int8_checkpoint(model, self.bundle, self.device).eval()
else:
self.model = load_checkpoint_and_dispatch(model, str(self.bundle / "model.safetensors"),
device_map={"": 0}, strict=True).eval()
if int8:
for name in quantization["modules"]:
layer = self.model.get_submodule(name)
if layer.weight.dtype != torch.int8 or layer.weight.SCB is None or not torch.isfinite(layer.weight.SCB).all():
raise ValueError("an INT8 weight or row scale was not restored correctly")
if any(buffer.dtype != torch.float32 for name, buffer in backbone.named_buffers() if name.endswith("inv_freq")):
raise ValueError("positional-frequency buffers must retain their original FP32 precision")
if any("lora_" in name or ".base_layer." in name for name, _ in self.model.named_parameters()):
raise ValueError("a dense model must not construct runtime adapter branches")
for parameter in self.model.parameters():
parameter.requires_grad_(False)
def predict_logits(self, request):
prepared, encoded = self.compile(request)
self.load()
import torch
batch = self.runtime.collate_records([encoded], self.tokenizer.pad_token_id, torch.device(self.device))
with torch.no_grad():
logits = [value.detach().float().cpu() for value in self.model(batch)[0]]
if len(logits) != len(prepared.fields) or any(not torch.isfinite(value).all() for value in logits):
raise ValueError("invalid model output")
return prepared, encoded, logits
def predict(self, request, *, include_logits=False):
prepared, encoded, logits = self.predict_logits(request)
return format_response(prepared, encoded, logits, include_logits=include_logits)
def install_int8_layers(backbone, bundle):
import torch
import bitsandbytes as bnb
quantization = read_json(bundle / "quantization_config.json")
if (quantization.get("format") != "sourcehat-rlcd-bnb-int8-dense-v1"
or quantization.get("bitsandbytes_version") != "0.50.2"
or quantization.get("threshold") != 6.0
or quantization.get("has_fp16_weights") is not False):
raise ValueError("unsupported INT8 quantization configuration")
names = quantization.get("modules", [])
expected = {"language_model." + name for name, layer in backbone.named_modules()
if isinstance(layer, torch.nn.Linear) and re.fullmatch(
r"model\.language_model\.layers\.\d+\.(?:linear_attn|self_attn|mlp)\.[a-z0-9_]+", name)}
if len(names) != 496 or len(set(names)) != 496 or set(names) != expected:
raise ValueError("quantization must cover exactly the 496 merged text linear layers")
for name in names:
relative = name.removeprefix("language_model.")
original = backbone.get_submodule(relative)
if not isinstance(original, torch.nn.Linear):
raise ValueError("INT8 target is not a text linear layer")
parent_name, leaf = relative.rsplit(".", 1)
layer = bnb.nn.Linear8bitLt(original.in_features, original.out_features,
bias=original.bias is not None, has_fp16_weights=False, threshold=6.0)
layer.weight = bnb.nn.Int8Params(torch.empty_like(original.weight, dtype=torch.int8),
requires_grad=False, has_fp16_weights=False)
if original.bias is not None:
layer.bias = torch.nn.Parameter(torch.empty_like(original.bias), requires_grad=False)
setattr(backbone.get_submodule(parent_name), leaf, layer)
def load_int8_checkpoint(model, bundle, device):
import torch
from accelerate.utils.modeling import set_module_tensor_to_device
from safetensors import safe_open
keys = set(model.state_dict())
quantization = read_json(bundle / "quantization_config.json")
scales = {name + ".SCB" for name in quantization["modules"]}
# Avoid a second GPU-sized state dict while materializing bitsandbytes parameters.
with safe_open(bundle / "model.safetensors", framework="pt", device="cpu") as tensors:
if set(tensors.keys()) != keys | scales:
raise ValueError("INT8 tensor inventory differs from the complete model")
for name in sorted(keys):
value = tensors.get_tensor(name)
scb_name = name.removesuffix(".weight") + ".SCB" if name.endswith(".weight") else None
statistics = tensors.get_tensor(scb_name) if scb_name in scales else None
if statistics is not None and value.dtype != torch.int8:
raise ValueError("a quantized text matrix must retain its INT8 storage")
set_module_tensor_to_device(model, name, device, value=value, fp16_statistics=statistics)
del value, statistics
for name, value in list(model.named_buffers()):
if value.is_meta:
raise ValueError("an uninitialized model buffer remains after INT8 loading")
if str(value.device) != device:
set_module_tensor_to_device(model, name, device, value=value)
if any(value.is_meta or str(value.device) != device for value in model.parameters()):
raise ValueError("INT8 loading must materialize all model parameters on the selected GPU")
return model
def format_response(prepared, encoded, logits, *, include_logits=False):
distributions, proposal, p_field_correct, scores, saved_logits = {}, {}, {}, {}, {}
for field, values in zip(prepared.fields, logits):
numbers = values.tolist() if hasattr(values, "tolist") else list(values)
ids = prepared.candidate_ids[field["id"]]
if len(numbers) != len(ids) or not all(math.isfinite(value) for value in numbers):
raise ValueError("finite logits must match all supplied candidates")
weights = [math.exp(value - max(numbers)) for value in numbers]
probabilities = [value / sum(weights) for value in weights]
fid = field["id"]
distributions[fid] = dict(zip(ids, probabilities))
index = max(range(len(ids)), key=probabilities.__getitem__)
proposal[fid] = ids[index]
p_field_correct[fid] = probabilities[index]
saved_logits[fid] = dict(zip(ids, numbers))
if field["field_type"] == "ordinal":
scores[fid] = sum(index * value for index, value in enumerate(probabilities))
result = {"format": "sourcehat-rlcd", "schema_version": SCHEMA_VERSION,
"proposal": proposal, "field_distributions": distributions, "p_field_correct": p_field_correct,
"expected_scores": scores, "p_object_correct": None, "p_action_success": None,
"p_safe": None, "p_workflow_success": None, "p_recoverable": None,
"metadata": {"base_model": BASE_MODEL, "base_revision": BASE_REVISION,
"compiled_tokens": len(encoded.input_ids), "reasoning": "disabled",
"field_probabilities": "unscaled model distributions", "action_policy": "not applied"}}
if include_logits:
result["field_logits"] = saved_logits
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--request", type=Path, required=True)
parser.add_argument("--bundle", type=Path, default=Path(__file__).resolve().parent)
parser.add_argument("--base-model-path", type=Path)
parser.add_argument("--local-files-only", action="store_true")
parser.add_argument("--device", default="cuda:0", choices=("cuda:0",))
parser.add_argument("--include-logits", action="store_true")
args = parser.parse_args()
try:
request = read_json(args.request)
prepare_request(request)
model = DecisionModel(args.bundle, base_model_path=args.base_model_path,
local_files_only=args.local_files_only, device=args.device)
print(json.dumps(model.predict(request, include_logits=args.include_logits), allow_nan=False))
except (ValueError, OSError, RuntimeError, TypeError, KeyError) as exc:
print(json.dumps({"error": {"type": type(exc).__name__, "message": str(exc)}}, allow_nan=False), file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())