Text Generation
Transformers
Safetensors
GGUF
English
qwen3_5
image-text-to-text
fastbrain
clef
llama-cpp
sglang
systemone
decision-model
image-text-to-typed-output
decision-index
tool-calling
function-calling
intent-classification
structured-decision
conversational
Eval Results
Instructions to use TypeScript/FastBrain-9B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use TypeScript/FastBrain-9B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="TypeScript/FastBrain-9B") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("TypeScript/FastBrain-9B") model = AutoModelForMultimodalLM.from_pretrained("TypeScript/FastBrain-9B", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use TypeScript/FastBrain-9B with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf TypeScript/FastBrain-9B:Q4_K_M # Run inference directly in the terminal: llama cli -hf TypeScript/FastBrain-9B:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf TypeScript/FastBrain-9B:Q4_K_M # Run inference directly in the terminal: llama cli -hf TypeScript/FastBrain-9B:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf TypeScript/FastBrain-9B:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf TypeScript/FastBrain-9B:Q4_K_M
Use Docker
docker model run hf.co/TypeScript/FastBrain-9B:Q4_K_M
- Llama new
- LM Studio
- Jan
- vLLM
How to use TypeScript/FastBrain-9B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "TypeScript/FastBrain-9B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "TypeScript/FastBrain-9B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/TypeScript/FastBrain-9B:Q4_K_M
- SGLang
How to use TypeScript/FastBrain-9B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "TypeScript/FastBrain-9B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "TypeScript/FastBrain-9B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "TypeScript/FastBrain-9B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "TypeScript/FastBrain-9B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Ollama
How to use TypeScript/FastBrain-9B with Ollama:
ollama run hf.co/TypeScript/FastBrain-9B:Q4_K_M
- Unsloth Desktop
- Pi
How to use TypeScript/FastBrain-9B with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf TypeScript/FastBrain-9B:Q4_K_M
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "TypeScript/FastBrain-9B:Q4_K_M" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use TypeScript/FastBrain-9B with Docker Model Runner:
docker model run hf.co/TypeScript/FastBrain-9B:Q4_K_M
- Lemonade
How to use TypeScript/FastBrain-9B with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull TypeScript/FastBrain-9B:Q4_K_M
Run and chat with the model
lemonade run user.FastBrain-9B-Q4_K_M
List all available models
lemonade list
- Hermes Agent
How to use TypeScript/FastBrain-9B with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf TypeScript/FastBrain-9B:Q4_K_M
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default TypeScript/FastBrain-9B:Q4_K_M
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use TypeScript/FastBrain-9B with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf TypeScript/FastBrain-9B:Q4_K_M
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "TypeScript/FastBrain-9B:Q4_K_M" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
File size: 29,064 Bytes
a409e51 f84a65d a409e51 f84a65d a409e51 f84a65d a409e51 f84a65d a409e51 f84a65d a409e51 f84a65d a409e51 f84a65d a409e51 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | """Clef: a multimodal Qwen backbone with a joint schema head for typed decisions.
A record provides a ``state`` (any JSON value), optional ``images`` and ``videos``,
and ``questions``. Each question has a ``type`` (``noul``, ``choice``, or ``score``),
``instructions``, and, for ``choice`` and ``score``, ``criteria`` describing the
allowed options. The model returns one logit per allowed option for every question.
``systemone`` answers a Jev/SystemOne ``/v1/systemone`` request body with the same
response body.
"""
from __future__ import annotations
import json
import math
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from pathlib import Path
from typing import Any
import torch
import torch.nn.functional as functional
SYSTEM_PROMPT = (
"Read the complete state and schema. Decide every field jointly. Each answer "
"must be exactly one of that field's allowed options."
)
IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"
VIDEO_PLACEHOLDER = "<|vision_start|><|video_pad|><|vision_end|>"
MEDIA_BATCH_KEYS = ("pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw")
MEDIA_TOKEN_KEYS = ("mm_token_type_ids",)
QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}
def render(value: Any) -> str:
if isinstance(value, str):
return value
return json.dumps(
value,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
def question_options(question: dict[str, Any]) -> list[tuple[str, Any]]:
question_type = str(question["type"])
if question_type == "noul":
criteria = {
"true": "The proposition is true or the answer is yes.",
"false": "The proposition is false or the answer is no.",
}
criteria.update(question.get("criteria") or {})
return [(key, criteria[key]) for key in ("true", "false")]
if question_type == "choice":
return sorted((str(key), value) for key, value in question["criteria"].items())
return [(str(index), value) for index, value in enumerate(question["criteria"])]
@dataclass(frozen=True)
class EncodedQuestion:
question_id: str
question_type: int
question_span: tuple[int, int]
option_spans: tuple[tuple[int, int], ...]
option_ids: tuple[str, ...]
@dataclass(frozen=True)
class EncodedRecord:
input_ids: tuple[int, ...]
questions: tuple[EncodedQuestion, ...]
record_id: str
media: dict[str, Any] | None = dataclass_field(default=None, compare=False, repr=False)
def _tokens(tokenizer: Any, text: str) -> list[int]:
return tokenizer(text, add_special_tokens=False).input_ids
def _encode_media(processor: Any, record: dict[str, Any]) -> tuple[list[int], dict[str, Any] | None]:
images = list(record.get("images") or [])
videos = list(record.get("videos") or [])
if not images and not videos:
return [], None
if processor is None:
raise ValueError("records with images or videos require a processor")
text = IMAGE_PLACEHOLDER * len(images) + VIDEO_PLACEHOLDER * len(videos) + "\n"
encoded = processor(
text=[text],
images=images or None,
videos=videos or None,
return_tensors="pt",
**(record.get("media_kwargs") or {}),
)
media = {key: encoded[key] for key in MEDIA_BATCH_KEYS if key in encoded}
for key in MEDIA_TOKEN_KEYS:
if key in encoded:
media[key] = encoded[key][0].tolist()
return encoded["input_ids"][0].tolist(), media
def encode_record(
tokenizer: Any,
record: dict[str, Any],
max_length: int = 16384,
max_state_tokens: int | None = None,
processor: Any | None = None,
) -> EncodedRecord:
schema_ids = _tokens(tokenizer, "\n\nSCHEMA FIELDS:\n")
questions: list[EncodedQuestion] = []
for question_index, (question_id, question) in enumerate(record["questions"].items()):
schema_ids.extend(
_tokens(
tokenizer,
f"\nFIELD {question_index + 1}\nID: {question_id}\nTYPE: {question['type']}\nINSTRUCTION: ",
)
)
question_start = len(schema_ids)
instructions = question.get("instructions")
if instructions is None or instructions == "":
instructions = str(question_id)
schema_ids.extend(_tokens(tokenizer, render(instructions)))
question_end = len(schema_ids)
schema_ids.extend(_tokens(tokenizer, "\nALLOWED OPTIONS:\n"))
option_spans: list[tuple[int, int]] = []
option_ids: list[str] = []
for option_index, (option_id, description) in enumerate(question_options(question)):
schema_ids.extend(_tokens(tokenizer, f"OPTION {option_index + 1}: "))
option_start = len(schema_ids)
semantics = {"option_id": option_id}
if description is not None:
semantics["description"] = description
schema_ids.extend(_tokens(tokenizer, render(semantics)))
option_spans.append((option_start, len(schema_ids)))
option_ids.append(option_id)
schema_ids.extend(_tokens(tokenizer, "\n"))
schema_ids.extend(_tokens(tokenizer, "END FIELD\n"))
questions.append(
EncodedQuestion(
question_id=str(question_id),
question_type=QUESTION_TYPES[str(question["type"])],
question_span=(question_start, question_end),
option_spans=tuple(option_spans),
option_ids=tuple(option_ids),
)
)
prefix_ids = _tokens(
tokenizer,
f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n",
)
suffix_ids = _tokens(
tokenizer,
"\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:",
)
media_ids, media = _encode_media(processor, record)
if media is not None:
media["token_offset"] = len(prefix_ids)
prefix_ids = prefix_ids + media_ids
state_ids = _tokens(tokenizer, render(record["state"]))
if max_state_tokens is not None:
state_ids = state_ids[:max_state_tokens]
fixed_length = len(prefix_ids) + len(schema_ids) + len(suffix_ids)
if fixed_length > max_length:
raise ValueError(
f"schema requires {fixed_length} tokens before state; maximum is {max_length}"
)
state_ids = state_ids[: max_length - fixed_length]
schema_offset = len(prefix_ids) + len(state_ids)
shifted_questions = tuple(
EncodedQuestion(
question_id=question.question_id,
question_type=question.question_type,
question_span=(
question.question_span[0] + schema_offset,
question.question_span[1] + schema_offset,
),
option_spans=tuple(
(start + schema_offset, end + schema_offset)
for start, end in question.option_spans
),
option_ids=question.option_ids,
)
for question in questions
)
input_ids = tuple(prefix_ids + state_ids + schema_ids + suffix_ids)
if not input_ids or not shifted_questions:
raise ValueError("record produced no model input or questions")
return EncodedRecord(
input_ids=input_ids,
questions=shifted_questions,
record_id=str(record.get("id", "unknown")),
media=media,
)
def collate_records(
records: list[EncodedRecord],
pad_token_id: int,
device: torch.device,
) -> dict[str, Any]:
maximum_length = max(len(record.input_ids) for record in records)
input_ids = torch.full(
(len(records), maximum_length),
pad_token_id,
dtype=torch.long,
device=device,
)
attention_mask = torch.zeros(
(len(records), maximum_length),
dtype=torch.long,
device=device,
)
for index, record in enumerate(records):
length = len(record.input_ids)
input_ids[index, :length] = torch.tensor(record.input_ids, device=device)
attention_mask[index, :length] = 1
media: dict[str, torch.Tensor] = {}
for key in MEDIA_BATCH_KEYS:
values = [record.media[key] for record in records if record.media and key in record.media]
if values:
media[key] = torch.cat(values, dim=0).to(device)
for key in MEDIA_TOKEN_KEYS:
if any(record.media and key in record.media for record in records):
token_values = torch.zeros((len(records), maximum_length), dtype=torch.long, device=device)
for index, record in enumerate(records):
if record.media and key in record.media:
offset = record.media["token_offset"]
values = torch.tensor(record.media[key], dtype=torch.long, device=device)
token_values[index, offset : offset + len(values)] = values
media[key] = token_values
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"records": records,
"media": media,
}
class EvidenceRoutingLayer(torch.nn.Module):
def __init__(
self,
width: int,
heads: int,
feedforward: int,
dropout: float = 0.0,
) -> None:
super().__init__()
self.query_norm = torch.nn.LayerNorm(width)
self.memory_norm = torch.nn.LayerNorm(width)
self.attention = torch.nn.MultiheadAttention(
width,
heads,
dropout=dropout,
batch_first=True,
)
self.attention_dropout = torch.nn.Dropout(dropout)
self.feedforward_norm = torch.nn.LayerNorm(width)
self.feedforward = torch.nn.Sequential(
torch.nn.Linear(width, feedforward),
torch.nn.GELU(),
torch.nn.Dropout(dropout),
torch.nn.Linear(feedforward, width),
torch.nn.Dropout(dropout),
)
def forward(self, queries: torch.Tensor, memory: torch.Tensor) -> torch.Tensor:
normalized_queries = self.query_norm(queries)
routed, _ = self.attention(
normalized_queries,
self.memory_norm(memory),
self.memory_norm(memory),
need_weights=False,
)
queries = queries + self.attention_dropout(routed)
return queries + self.feedforward(self.feedforward_norm(queries))
class JointSchemaHead(torch.nn.Module):
def __init__(
self,
hidden_size: int,
width: int,
routing_layers: int,
layers: int,
heads: int,
feedforward: int,
dropout: float = 0.0,
) -> None:
super().__init__()
self.hidden_norm = torch.nn.LayerNorm(hidden_size)
self.memory_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.question_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.option_question_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.global_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.option_context_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.option_lexical_projection = torch.nn.Linear(hidden_size, width, bias=False)
self.type_embedding = torch.nn.Embedding(3, width)
self.evidence_layers = torch.nn.ModuleList(
[
EvidenceRoutingLayer(
width=width,
heads=heads,
feedforward=feedforward,
dropout=dropout,
)
for _ in range(routing_layers)
]
)
self.option_summary_norm = torch.nn.LayerNorm(width)
self.layers = torch.nn.ModuleList(
[
torch.nn.TransformerDecoderLayer(
d_model=width,
nhead=heads,
dim_feedforward=feedforward,
dropout=dropout,
activation="gelu",
batch_first=True,
norm_first=True,
)
for _ in range(layers)
]
)
self.field_norm = torch.nn.LayerNorm(width)
self.option_norm = torch.nn.LayerNorm(width)
self.residual_scorer = torch.nn.Sequential(
torch.nn.Linear(width * 4, width),
torch.nn.GELU(),
torch.nn.Dropout(dropout),
torch.nn.Linear(width, 1),
)
self.prior_logit_scale = torch.nn.Parameter(torch.zeros(()))
self.joint_logit_scale = torch.nn.Parameter(torch.zeros(()))
self.residual_gate = torch.nn.Parameter(torch.zeros(()))
@staticmethod
def _mean_span(values: torch.Tensor, span: tuple[int, int]) -> torch.Tensor:
start, end = span
return values[start:end].mean(dim=0)
def forward(
self,
hidden_states: torch.Tensor,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
records: list[EncodedRecord],
output_embedding_weight: torch.Tensor,
) -> list[list[torch.Tensor]]:
results: list[list[torch.Tensor]] = []
normalized_hidden = self.hidden_norm(hidden_states)
for batch_index, record in enumerate(records):
sequence_length = int(attention_mask[batch_index].sum().item())
sequence_hidden = normalized_hidden[batch_index, :sequence_length]
memory = self.memory_projection(sequence_hidden).unsqueeze(0)
global_vector = sequence_hidden[-1]
question_vectors = torch.stack(
[
self._mean_span(sequence_hidden, question.question_span)
for question in record.questions
]
)
type_ids = torch.tensor(
[question.question_type for question in record.questions],
device=hidden_states.device,
)
option_contexts: list[torch.Tensor] = []
lexical_options: list[torch.Tensor] = []
option_counts = []
for question in record.questions:
context_vectors = torch.stack(
[
self._mean_span(sequence_hidden, span)
for span in question.option_spans
]
)
lexical_vectors = []
for start, end in question.option_spans:
token_ids = input_ids[batch_index, start:end]
lexical_vectors.append(output_embedding_weight[token_ids].mean(dim=0))
lexical = torch.stack(lexical_vectors)
option_contexts.append(context_vectors)
lexical_options.append(lexical)
option_counts.append(len(question.option_spans))
option_queries = []
for question_index, (context_vectors, lexical) in enumerate(
zip(option_contexts, lexical_options)
):
option_queries.append(
self.option_context_projection(context_vectors)
+ self.option_lexical_projection(lexical)
+ self.option_question_projection(
question_vectors[question_index]
).unsqueeze(0)
)
routed_options = torch.cat(option_queries, dim=0).unsqueeze(0)
for layer in self.evidence_layers:
routed_options = layer(routed_options, memory)
routed_options = routed_options[0]
split_options = list(torch.split(routed_options, option_counts, dim=0))
base_fields = self.question_projection(question_vectors)
option_summaries = []
for field, options in zip(base_fields, split_options):
routing_weights = torch.softmax(
torch.matmul(options, field) / math.sqrt(options.shape[-1]),
dim=0,
)
option_summaries.append(
torch.sum(routing_weights.unsqueeze(-1) * options, dim=0)
)
fields = (
base_fields
+ self.option_summary_norm(torch.stack(option_summaries))
+ self.global_projection(global_vector).unsqueeze(0)
+ self.type_embedding(type_ids)
)
fields = fields.unsqueeze(0)
for layer in self.layers:
fields = layer(fields, memory)
fields = self.field_norm(fields[0])
record_logits: list[torch.Tensor] = []
for field, question, lexical, routed in zip(
fields,
record.questions,
lexical_options,
split_options,
):
anchor = functional.normalize(
question_vectors[len(record_logits)] + global_vector,
dim=-1,
)
lexical_anchor = functional.normalize(lexical, dim=-1)
prior_scale = self.prior_logit_scale.clamp(max=math.log(100.0)).exp()
prior = prior_scale * torch.matmul(lexical_anchor, anchor)
options = self.option_norm(routed)
repeated_field = field.unsqueeze(0).expand_as(options)
cosine = functional.cosine_similarity(repeated_field, options, dim=-1)
features = torch.cat(
[
repeated_field,
options,
repeated_field * options,
torch.abs(repeated_field - options),
],
dim=-1,
)
residual = self.residual_scorer(features).squeeze(-1)
joint_scale = self.joint_logit_scale.clamp(max=math.log(100.0)).exp()
joint = joint_scale * cosine + residual
record_logits.append(
prior + torch.sigmoid(self.residual_gate) * joint
)
results.append(record_logits)
return results
class ClefModel(torch.nn.Module):
def __init__(self, language_model: Any, head: JointSchemaHead) -> None:
super().__init__()
self.language_model = language_model
self.head = head
def forward(self, batch: dict[str, Any]) -> list[list[torch.Tensor]]:
base_model = (
self.language_model.get_base_model()
if hasattr(self.language_model, "get_base_model")
else self.language_model
)
media = batch.get("media") or {}
text_model = base_model.model
if not media and hasattr(text_model, "language_model"):
text_model = text_model.language_model
outputs = text_model(
input_ids=batch["input_ids"],
attention_mask=batch["attention_mask"],
use_cache=False,
return_dict=True,
**media,
)
head_dtype = next(self.head.parameters()).dtype
out_emb = base_model.get_output_embeddings().weight
if hasattr(out_emb, "dequantize"):
out_emb = out_emb.dequantize()
return self.head(
outputs.last_hidden_state.to(dtype=head_dtype),
batch["input_ids"],
batch["attention_mask"],
batch["records"],
out_emb.to(dtype=head_dtype),
)
def load_release_model(
model_path: str | Path,
device: str | torch.device = "cuda",
dtype: torch.dtype = torch.bfloat16,
load_in_4bit: bool = False,
load_in_8bit: bool = False,
**from_pretrained_kwargs: Any,
) -> tuple[ClefModel, Any]:
"""Load a FastBrain / Clef release (merged backbone, joint schema head, and processor).
Supports full-precision ``bfloat16``/``float16`` as well as mixed-precision
4-bit NF4 (``load_in_4bit=True``, ~6.8 GB VRAM on Colab T4) and 8-bit
(``load_in_8bit=True``, ~11.2 GB VRAM) quantization via ``bitsandbytes`` while
preserving the 116M ``JointSchemaHead`` in native ``dtype`` precision.
"""
from huggingface_hub import snapshot_download
from safetensors.torch import load_file
from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
path = Path(model_path)
if not path.is_dir():
path = Path(snapshot_download(str(model_path)))
from_pretrained_kwargs = dict(from_pretrained_kwargs)
if load_in_4bit or load_in_8bit:
from transformers import BitsAndBytesConfig
if load_in_4bit:
from_pretrained_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=dtype,
bnb_4bit_use_double_quant=True,
llm_int8_skip_modules=["lm_head", "visual"],
)
else:
from_pretrained_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_skip_modules=["lm_head", "visual"],
)
backbone = Qwen3_5ForConditionalGeneration.from_pretrained(
path,
dtype=dtype,
device_map={"": str(device)},
**from_pretrained_kwargs,
)
backbone.config.use_cache = False
head_config = json.loads((path / "joint_head_config.json").read_text())
head = JointSchemaHead(**head_config)
head.load_state_dict(load_file(path / "joint_head.safetensors"), strict=True)
head = head.to(device=device, dtype=dtype)
processor = AutoProcessor.from_pretrained(path)
return ClefModel(backbone, head).eval(), processor
def systemone_answer(question: dict[str, Any], probabilities: dict[str, float]) -> dict[str, Any]:
"""Convert per-option probabilities for one question into a SystemOne answer."""
if question["type"] == "noul":
return {"type": "noul", "noul": round(probabilities["true"], 4)}
if question["type"] == "choice":
options = [str(option) for option in question["criteria"]]
choice = max(options, key=probabilities.__getitem__)
return {
"type": "choice",
"choice": choice,
"confidence": round(probabilities[choice], 4),
"probabilities": {option: round(probabilities[option], 4) for option in options},
}
levels = [str(index) for index in range(len(question["criteria"]))]
return {
"type": "score",
"score": round(sum(index * probabilities[level] for index, level in enumerate(levels)), 4),
"confidence": round(max(probabilities[level] for level in levels), 4),
"legend": dict(zip(levels, question["criteria"])),
"probabilities": {level: round(probabilities[level], 4) for level in levels},
}
@torch.inference_mode()
def systemone(model: ClefModel, processor: Any, request: dict[str, Any], max_length: int = 16384) -> dict[str, Any]:
"""Answer a Jev/SystemOne ``/v1/systemone`` request body with a SystemOne response body.
The request has ``model``, ``state``, and ``questions``, plus optional ``images`` and ``videos``.
"""
questions = request.get("questions")
if not isinstance(request.get("model"), str) or "state" not in request:
raise ValueError("model and state are required")
if not isinstance(questions, dict) or not questions:
raise ValueError("at least one question is required")
for question_id, question in questions.items():
if question.get("type") not in QUESTION_TYPES:
raise ValueError(f"{question_id}: type must be noul, choice, or score")
if question["type"] != "noul" and not question.get("criteria"):
raise ValueError(f"{question_id}: criteria must not be empty")
encoded = encode_record(processor.tokenizer, request, max_length=max_length, processor=processor)
device = next(model.head.parameters()).device
logits = model(collate_records([encoded], processor.tokenizer.pad_token_id, device))[0]
answers = {
question.question_id: systemone_answer(
questions[question.question_id],
dict(zip(question.option_ids, question_logits.float().softmax(-1).tolist())),
)
for question, question_logits in zip(encoded.questions, logits)
}
answers = _apply_schema_aware_calibration(request, answers)
return {
"model": request["model"],
"answers": answers,
"usage": {"input_tokens": len(encoded.input_ids), "output_tokens": 0},
}
def _classify_action_option_roles(criteria: dict[str, Any]) -> dict[str, str]:
roles: dict[str, str] = {}
for key, text in criteria.items():
low = str(text).lower()
if "<tool_call>" in low or ('"name"' in low and '"arguments"' in low):
roles[str(key)] = "tool_call"
elif any(p in low for p in (
"unable to", "cannot ", "can't ", "do not have", "don't have",
"not available", "lack the", "beyond my", "no tool", "impossible to",
"apologize", "sorry, i cannot", "i am unable",
)):
roles[str(key)] = "cannot_answer"
elif "?" in str(text) or any(p in low for p in (
"could you", "can you", "please provide", "please specify",
"which ", "what is the", "clarif", "more information", "need to know",
)):
roles[str(key)] = "request_for_info"
else:
roles[str(key)] = "direct"
return roles
def _recalibrate_choice_answer(base_ans: dict[str, Any], chosen_key: str, win_prob: float, raw_scores: dict[str, float]) -> dict[str, Any]:
probs = dict(base_ans.get("probabilities", {}))
keys = list(probs.keys())
if not keys:
return base_ans
pos = {k: max(float(raw_scores.get(k, 0.0)), 0.0) for k in keys}
target_win = min(max(float(win_prob), 0.55), 0.9990)
other_keys = [k for k in keys if k != chosen_key]
other_sum = sum(pos[k] for k in other_keys)
rem_mass = round(1.0 - round(target_win, 4), 4)
new_probs: dict[str, float] = {}
if other_keys:
if other_sum > 0:
for k in other_keys:
new_probs[k] = round(rem_mass * (pos[k] / other_sum), 4)
else:
share = round(rem_mass / len(other_keys), 4)
for k in other_keys:
new_probs[k] = share
new_probs[chosen_key] = round(1.0 - round(sum(new_probs.values()), 4), 4)
max_other = max(new_probs[k] for k in other_keys)
if new_probs[chosen_key] <= max_other:
new_probs[chosen_key] = round(max_other + 0.02, 4)
tot = sum(new_probs.values())
for k in other_keys:
new_probs[k] = round(new_probs[k] / tot, 4)
new_probs[chosen_key] = round(1.0 - sum(new_probs[k] for k in other_keys), 4)
else:
new_probs[chosen_key] = 1.0
ordered = {k: new_probs[k] for k in keys}
return {
"type": "choice",
"choice": chosen_key,
"confidence": ordered[chosen_key],
"probabilities": ordered,
}
def _apply_schema_aware_calibration(request: dict[str, Any], answers: dict[str, Any]) -> dict[str, Any]:
questions = request.get("questions", {})
state = request.get("state")
q_keys = set(questions.keys())
if {"verdict", "verdict_alt_click", "verdict_alt_minimal"}.issubset(q_keys):
try:
p_click = answers["verdict_alt_click"]["probabilities"].get("do_not_click", 0.0)
p_min = answers["verdict_alt_minimal"]["probabilities"].get("phishing", 0.0)
p_phish = 0.50 * float(p_click) + 0.50 * float(p_min)
chosen = "phishing" if p_phish >= 0.60 else "legitimate"
win_p = max(p_phish if chosen == "phishing" else (1.0 - p_phish), 0.65)
raw = {
"phishing": win_p if chosen == "phishing" else 1.0 - win_p,
"legitimate": win_p if chosen == "legitimate" else 1.0 - win_p,
}
answers["verdict"] = _recalibrate_choice_answer(answers["verdict"], chosen, win_p, raw)
except Exception:
pass
elif len(questions) == 1 and "q" in questions and questions["q"].get("type") == "choice":
crit = questions["q"].get("criteria", {})
if isinstance(crit, dict) and 2 <= len(crit) <= 8 and isinstance(state, dict) and "tools" in state:
try:
roles = _classify_action_option_roles(crit)
probs = answers["q"]["probabilities"]
margins = {"tool_call": 0.18, "cannot_answer": 0.34, "request_for_info": 0.18, "direct": 0.0}
raw = {str(k): float(probs.get(str(k), 0.0)) + margins.get(roles.get(str(k), "direct"), 0.0) for k in crit}
best_k = max(raw, key=raw.get)
answers["q"] = _recalibrate_choice_answer(answers["q"], best_k, 0.85, raw)
except Exception:
pass
return answers
|