Deep dive into CLEF with step by step walkthrough of its model architecture in PyTorch

Step by step walkthrough of the model architecture of CLEF in PyTorch.

In this blog post, I explain the model architecture of CLEF, one of the first decision models by Cloudflare. We will walk through the model architecture and all tensor shapes step by step. I would recommend to anyone who is looking to understand System One model architectures in depth.

Author

Aman Arora

Published

November 25, 2026

In this blog post, I will take you through the complete model architecture of Clef (Cloudflare 2026), by Cloudflare.

I was interested and curious about understanding the complete model architecture and inner workings of System One models or Decision models. So I started with Clef. Why Clef? It was one of the cleanest model architectures and public code sample to start with and helps build intuition on the inner workings of Decision models.

As part of this blog post - I will take you through the complete steps - demystifying everything, from data processing, to Qwen backbones, to JointSchemaHead and also EvidenceRoutingLayer. I will reference Clef’s model source as I begin to dive deeper. In the runnable code cells below, I use the 9B Cloudflare/clef-flash (Qwen3.5-9B) variant so it runs locally on CPU - the JointSchemaHead architecture is identical to the 27B Cloudflare/clef (Qwen3.8-27B).

Figure 1: Clef model architecture overview

This post does not cover:

I am going to assume that the reader has a good understanding of PyTorch, self and cross attention and is curious to dive deeper into the inner workings of Decision Models. For an introduction to decision models, please refer to my previous blog post - Jev: A New Way to Make Probabilistic Decisions (Arora 2026).

Arora, Aman. 2026. “Jev: A New Way to Make Probabilistic Decisions.” September 19. https://amaarora.github.io/posts/2026-19-09-jev-intro.html.

With that being said, let’s get started.

1 System One API

Before we dive deeper into the model architecture, let’s take a look at the System One API and the inputs and outputs.

We will work with the following example in this blog post:

record = {
    "state": {"invoice": {"vendor": "Acme", "total": 1250.0, "currency": "USD", "status": "overdue"}},
    "questions": {
        "status": {
            "type": "choice",
            "instructions": "What is the invoice status?",
            "criteria": {"paid": "Invoice is paid.", "overdue": "Invoice is past due.", "draft": "Not sent."},
        },
        "large": {"type": "noul", "instructions": "Is the total above 1000 USD?"},
    },
}
Code
from huggingface_hub import snapshot_download
from joint_schema_model import load_release_model, systemone

record = {
    "state": {
        "invoice": {
            "vendor": "Acme",
            "total": 1250.0,
            "currency": "USD",
            "status": "overdue",
        }
    },
    "questions": {
        "status": {
            "type": "choice",
            "instructions": "What is the invoice status?",
            "criteria": {
                "paid": "Invoice is paid.",
                "overdue": "Invoice is past due.",
                "draft": "Not sent.",
            },
        },
        "large": {"type": "noul", "instructions": "Is the total above 1000 USD?"},
    },
    "model": "clef-flash",
}

path = snapshot_download("Cloudflare/clef-flash")
model, processor = load_release_model(path, device="cpu")
out = systemone(model, processor, record)
out
/Users/aroraagi/GIT_REPOS/jev-open-source/CLEF/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
Fetching 19 files: 100%|██████████| 19/19 [00:00<00:00, 2161.07it/s]
W1126 08:49:32.623000 79507 torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|██████████| 760/760 [00:00<00:00, 4201.49it/s]
[transformers] `causal_conv1d_fn` is falling back to its reference PyTorch implementation because `causal_conv1d` is not installed. This is correct but much slower; install `causal_conv1d` for the optimized kernel.
[transformers] `chunk_gated_delta_rule` is falling back to its reference PyTorch implementation because `flash-linear-attention` is not installed. This is correct but much slower; install `flash-linear-attention` for the optimized kernel.
{'model': 'clef-flash',
 'answers': {'status': {'type': 'choice',
   'choice': 'overdue',
   'confidence': 0.973,
   'probabilities': {'paid': 0.0176, 'overdue': 0.973, 'draft': 0.0094}},
  'large': {'type': 'noul', 'noul': 0.9734}},
 'usage': {'input_tokens': 260, 'output_tokens': 0}}

As we can see from the output above, the decision model is correctly able to identify the correct option for each of the two questions - “What is the invoice status?” & “Is the total above 1000 USD?”.

For the invoice status, the API correctly responds ‘overdue’ with 0.973 probability. And similarly for total amount, it correctly responds as yes with probability 0.9734.

But there is a lot that is going on underneath. When I first started using decision models, the first questions that came to my mind are:

  1. How is it different from classification?
  2. How is every question processed in just one forward pass?
  3. Is it possible for each question to have a separate number of options? How does that even work?
  4. What is the total possible context limit of state and questions?
  5. Does ordering of options impact the probability?
  6. Are decision models deterministic or non-deterministic?

Well, question-6 is easy to answer. Let’s run the same cell again.

Code
out = systemone(model, processor, record)
out
{'model': 'clef-flash',
 'answers': {'status': {'type': 'choice',
   'choice': 'overdue',
   'confidence': 0.973,
   'probabilities': {'paid': 0.0176, 'overdue': 0.973, 'draft': 0.0094}},
  'large': {'type': 'noul', 'noul': 0.9734}},
 'usage': {'input_tokens': 260, 'output_tokens': 0}}

Looking at the output, it is completely identical to what we had when we first ran the systemone API. Therefore, we can confirm that System One models are deterministic - unlike autoregressive LLMs, there is no sampling loop (no temperature or top_p random token draws), just a single forward pass followed by a softmax (aside from minor GPU kernel/batching floating-point variance). But there were still a lot more questions in my head that I wanted answers to. Let’s dig deeper and look at the model source.

Code
from typing import Any

import torch
from joint_schema_model import (
    ClefModel,
    collate_records,
    encode_record,
    systemone_answer,
)

QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}


@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.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)
    }
    return {
        "model": request["model"],
        "answers": answers,
        "usage": {"input_tokens": len(encoded.input_ids), "output_tokens": 0},
    }

Diving deeper into the source code of systemone - we can infer:

  1. The processor encodes input batch to get encoded values. We will look at it next.
  2. One forward pass through ClefModel returns required logits which gets converted to answers with the help of systemone_answer function.

Let’s look at the encode_record function next.

2 Data Processing

Code
encoded = encode_record(processor.tokenizer, record, processor=processor)
encoded
EncodedRecord(input_ids=(248045, 8678, 198, 4274, 279, 4434, 1528, 321, 10485, 13, 95462, 1396, 2002, 50407, 13, 8618, 4087, 1902, 381, 6681, 799, 314, 421, 2002, 579, 5252, 2519, 13, 248046, 198, 248045, 846, 198, 23852, 25, 198, 4754, 21529, 21624, 15501, 3147, 25895, 2129, 2738, 3147, 1908, 22906, 2129, 4873, 763, 16, 17, 20, 15, 13, 15, 1288, 18633, 3147, 11318, 2573, 29958, 271, 3423, 34651, 426, 32349, 25, 198, 198, 27806, 220, 16, 198, 887, 25, 2552, 198, 9222, 25, 5576, 198, 669, 55530, 25, 220, 3710, 369, 279, 23839, 2552, 30, 198, 51535, 1425, 49555, 25, 198, 32929, 220, 16, 25, 220, 4754, 4532, 3147, 2536, 3106, 46292, 1979, 816, 3147, 43494, 8934, 198, 32929, 220, 17, 25, 220, 4754, 4532, 3147, 33526, 369, 3162, 4016, 46292, 1979, 816, 3147, 1908, 22906, 8934, 198, 32929, 220, 18, 25, 220, 4754, 4532, 3147, 33526, 369, 6945, 46292, 1979, 816, 3147, 33530, 8934, 198, 4537, 38945, 198, 198, 27806, 220, 17, 198, 887, 25, 3349, 198, 9222, 25, 307, 10644, 198, 669, 55530, 25, 220, 3742, 279, 2702, 3294, 220, 16, 15, 15, 15, 18954, 30, 198, 51535, 1425, 49555, 25, 198, 32929, 220, 16, 25, 220, 4754, 4532, 3147, 760, 38749, 369, 804, 466, 279, 4087, 369, 9542, 46292, 1979, 816, 3147, 1802, 8934, 198, 32929, 220, 17, 25, 220, 4754, 4532, 3147, 760, 38749, 369, 867, 466, 279, 4087, 369, 874, 46292, 1979, 816, 3147, 3721, 8934, 198, 4537, 38945, 198, 198, 248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271, 25310, 3118, 7295, 34651, 41402, 23451, 50, 25), questions=(EncodedQuestion(question_id='status', question_type=1, question_span=(86, 92), option_spans=((103, 114), (120, 134), (140, 152)), option_ids=('draft', 'overdue', 'paid')), EncodedQuestion(question_id='large', question_type=0, question_span=(174, 185), option_spans=((196, 214), (220, 238)), option_ids=('true', 'false'))), record_id='unknown')

From above, we can see the encoded output is an EncodedRecord containing input_ids (what gets passed into the model) and a record_id. Every question also gets converted into an EncodedQuestion - each with a question_id, question_type, question_span, option_spans, and option_ids. Where each is relevant will become clearer as we further progress through this post.

But first, let’s decode the input_ids to see its values.

Code
print(processor.tokenizer.decode(encoded.input_ids))
<|im_start|>system
Read the complete state and schema. Decide every field jointly. Each answer must be exactly one of that field's allowed options.<|im_end|>
<|im_start|>user
STATE:
{"invoice":{"currency":"USD","status":"overdue","total":1250.0,"vendor":"Acme"}}

SCHEMA FIELDS:

FIELD 1
ID: status
TYPE: choice
INSTRUCTION: What is the invoice status?
ALLOWED OPTIONS:
OPTION 1: {"description":"Not sent.","option_id":"draft"}
OPTION 2: {"description":"Invoice is past due.","option_id":"overdue"}
OPTION 3: {"description":"Invoice is paid.","option_id":"paid"}
END FIELD

FIELD 2
ID: large
TYPE: noul
INSTRUCTION: Is the total above 1000 USD?
ALLOWED OPTIONS:
OPTION 1: {"description":"The proposition is true or the answer is yes.","option_id":"true"}
OPTION 2: {"description":"The proposition is false or the answer is no.","option_id":"false"}
END FIELD

<|im_end|>
<|im_start|>assistant
<think>

</think>

JOINT SCHEMA DECISIONS:

As can be seen above, running encode_record added a system prompt: “Read the complete state and schema. Decide every field jointly. Each answer must be exactly one of that field’s allowed options.”

It also, converted every question into a field which got encoded as:

FIELD 1
ID: status
TYPE: choice
INSTRUCTION: What is the invoice status?
ALLOWED OPTIONS:
OPTION 1: {"description":"Not sent.","option_id":"draft"}
OPTION 2: {"description":"Invoice is past due.","option_id":"overdue"}
OPTION 3: {"description":"Invoice is paid.","option_id":"paid"}
END FIELD

Finally, there is an empty thinking block -

<think>

</think>
Note

Why the empty <think>\n\n</think> block? In Qwen3/Qwen3.5’s chat template, an empty thinking block is the official enable_thinking=False convention - it signals the backbone to skip chain-of-thought mode and put its final hidden state straight into direct-answer mode right before JOINT SCHEMA DECISIONS:.

Assuming we have a trained model, let’s take a deeper look into the model architecture itself which is where all the token processing and magic happens.

3 ClefModel source code

Code
from typing import Any

import torch
from joint_schema_model import JointSchemaHead


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,
        )
        return self.head(
            outputs.last_hidden_state,
            batch["input_ids"],
            batch["attention_mask"],
            batch["records"],
            base_model.get_output_embeddings().weight,
        )

Just by reading the source code of ClefModel - here is what I could infer:

  • There is a language model backbone that processes the batch first
  • The last hidden state is then passed to a JointSchemaHead, which returns raw logits for each option (and systemone applies softmax right after to turn them into probabilities)

Example, 'large': {'type': 'noul', 'noul': 0.9734}}

Also, before we deep dive into the head - it would be helpful to just look at the shapes and values of outputs. Since this is a Qwen backbone, we can get the values by simply passing the input IDs to this backbone.

One could also set logging, print or debuggers throughout the codebase. I did the latter. :)

Code
from transformers import Qwen3_5ForConditionalGeneration

backbone = Qwen3_5ForConditionalGeneration.from_pretrained(
    path,
    dtype=torch.bfloat16,
    device_map={"": "cpu"},
)
backbone.config.use_cache = False
batch = collate_records([encoded], processor.tokenizer.pad_token_id, "cpu")
print(backbone.config)
backbone_outputs = backbone.model(
    batch["input_ids"], batch["attention_mask"], use_cache=False, return_dict=True
)
Loading weights: 100%|██████████| 760/760 [00:00<00:00, 3292.51it/s]
Qwen3_5Config {
  "architectures": [
    "Qwen3_5ForConditionalGeneration"
  ],
  "dtype": "bfloat16",
  "image_token_id": 248056,
  "model_type": "qwen3_5",
  "text_config": {
    "attention_bias": false,
    "attention_dropout": 0.0,
    "attn_output_gate": true,
    "bos_token_id": null,
    "dtype": "bfloat16",
    "eos_token_id": 248044,
    "full_attention_interval": 4,
    "head_dim": 256,
    "hidden_act": "silu",
    "hidden_size": 4096,
    "initializer_range": 0.02,
    "intermediate_size": 12288,
    "layer_types": [
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention",
      "linear_attention",
      "linear_attention",
      "linear_attention",
      "full_attention"
    ],
    "linear_conv_kernel_dim": 4,
    "linear_key_head_dim": 128,
    "linear_num_key_heads": 16,
    "linear_num_value_heads": 32,
    "linear_value_head_dim": 128,
    "mamba_ssm_dtype": "float32",
    "max_position_embeddings": 262144,
    "mlp_only_layers": [],
    "model_type": "qwen3_5_text",
    "mtp_num_hidden_layers": 0,
    "mtp_use_dedicated_embeddings": false,
    "num_attention_heads": 16,
    "num_hidden_layers": 32,
    "num_key_value_heads": 4,
    "pad_token_id": null,
    "rms_norm_eps": 1e-06,
    "rope_parameters": {
      "mrope_interleaved": true,
      "mrope_section": [
        11,
        11,
        10
      ],
      "partial_rotary_factor": 0.25,
      "rope_theta": 10000000,
      "rope_type": "default"
    },
    "tie_word_embeddings": false,
    "use_cache": true,
    "vocab_size": 248320
  },
  "tie_word_embeddings": false,
  "transformers_version": "5.24.1",
  "use_cache": false,
  "video_token_id": 248057,
  "vision_config": {
    "deepstack_visual_indexes": [],
    "depth": 27,
    "dtype": "bfloat16",
    "hidden_act": "gelu_pytorch_tanh",
    "hidden_size": 1152,
    "in_channels": 3,
    "initializer_range": 0.02,
    "intermediate_size": 4304,
    "model_type": "qwen3_5_vision",
    "num_heads": 16,
    "num_position_embeddings": 2304,
    "out_hidden_size": 4096,
    "patch_size": 16,
    "rope_parameters": {
      "rope_theta": 10000.0,
      "rope_type": "axial"
    },
    "spatial_merge_size": 2,
    "temporal_patch_size": 2
  },
  "vision_end_token_id": 248054,
  "vision_start_token_id": 248053
}
Code
backbone_outputs.last_hidden_state.shape
torch.Size([1, 260, 4096])

For every token_id, the model returns a 4096 long vector. These outputs are from Qwen 3.5 - and represent what we get after the model has completely processed the tokens. Remember, the last token has seen all the other tokens prior to it.

In the Clef Model, this \((1, 260, 4096)\) tensor is what gets passed to the JointSchemaHead. So now, we know that once the backbone has processed the inputs, which consist of state, questions, and options - the processed outputs are passed to the head as inputs.

For clef-flash, the shape of inputs to the JointSchemaHead is \((1, 260, 4096)\). Let’s look at the JointSchemaHead next and understand how this processed intermediate tensor is converted into probability scores for each option.

Note

Heads up, this is where the blog post gets most technical. So feel free to re-read the sections below multiple times if needed. And if you don’t understand any parts of it - Claude, GPTs or Gemini to the rescue. :)

4 JointSchemaHead - convert backbone processed tensors to output probability scores

In this section let’s deep dive into the JointSchemaHead and see how the intermediate processed tensor gets converted to probability scores. First, let’s just pass the tensor to this head and see what we get as output.

Code
head_outputs = model.head(
    backbone_outputs.last_hidden_state,
    batch["input_ids"],
    batch["attention_mask"],
    batch["records"],
    backbone.get_output_embeddings().weight,
)[0]
[head_output.float().softmax(-1).tolist() for head_output in head_outputs]
[[0.009427434764802456, 0.9729597568511963, 0.017612764611840248],
 [0.9734434485435486, 0.026556571945548058]]

To the reader, what you see above should feel exciting! This is the first time we actually see the probabilities come out of the Clef model! And based on these probabilities, the answer for the first question is Option-B (overdue, since option_ids are sorted alphabetically as ['draft', 'overdue', 'paid']), and for the second question is Option-A (true, from ['true', 'false']).

See how the probability scores of 0.973 and 0.9734 completely match the outputs of systemone API that we ran as the first cell of this blog post??

 'answers': {'status': {'type': 'choice',
   'choice': 'overdue',
   'confidence': 0.973,
   'probabilities': {'paid': 0.0176, 'overdue': 0.973, 'draft': 0.0094}},
  'large': {'type': 'noul', 'noul': 0.9734}},

Let’s deep dive into the JointSchemaHead source code now. We will proceed carefully and slowly so as to make sure we understand every single step and hop.

Code
import math

from joint_schema_model import EncodedRecord, EvidenceRoutingLayer
from torch.nn import functional


class JointSchemaHead(torch.nn.Module):
    def __init__(
        self,
        hidden_size: int,  # 4096
        width: int,  # 1024
        routing_layers: int,  # 2
        layers: int,  # 4
        heads: int,  # 16
        feedforward: int,  # 4096
        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,  # (1, 260, 4096)
        input_ids: torch.Tensor,  # (1, 260)
        attention_mask: torch.Tensor,  # (1, 260)
        records: list[EncodedRecord],
        output_embedding_weight: torch.Tensor,  # (248320, 4096)
    ) -> 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

There are 114 lines of source code in the forward pass of JointSchemaHead. Once we understand that, we understand the complete model architecture of Clef! That should sound exciting to my readers. Let’s proceed and break the forward pass into multiple tiny steps.

4.1 Step 1 - Turning input tokens into context_vectors, lexical_options, global_vector and shared memory

In this step, let’s look at the first part of the forward pass. We will build an intuition for the complete forward pass in Stages.

Looking at the inputs model.head(backbone_outputs.last_hidden_state, batch['input_ids'], batch['attention_mask'], batch['records'], backbone.get_output_embeddings().weight)[0] and the arguments for JointSchemaHead, we can infer:

hidden_states =  backbone_outputs.last_hidden_state
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
records = batch['records']
output_embedding_weight = backbone.get_output_embeddings().weight

Let’s use the above values and a single record and go through the forward pass as if we are going through the for loop.

Code
batch_index = 0
record = batch["records"][0]
hidden_states = backbone_outputs.last_hidden_state
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
records = batch["records"]
output_embedding_weight = backbone.get_output_embeddings().weight
(
    hidden_states.shape,
    input_ids.shape,
    attention_mask.shape,
    output_embedding_weight.shape,
)
(torch.Size([1, 260, 4096]),
 torch.Size([1, 260]),
 torch.Size([1, 260]),
 torch.Size([248320, 4096]))
Code
normalized_hidden = model.head.hidden_norm(hidden_states)
sequence_length = int(attention_mask[batch_index].sum().item())
sequence_hidden = normalized_hidden[batch_index, :sequence_length]
memory = model.head.memory_projection(sequence_hidden).unsqueeze(0)
global_vector = sequence_hidden[-1]
normalized_hidden.shape, sequence_hidden.shape, global_vector.shape, memory.shape
(torch.Size([1, 260, 4096]),
 torch.Size([260, 4096]),
 torch.Size([4096]),
 torch.Size([1, 260, 1024]))

Above, we simply normalize the hidden states, get sequence length, trim the hidden states up to :sequence_length and pass it through a linear layer of size \((4096, 1024)\) to get a memory tensor. This memory is a representation of the last_hidden_state with vector dimensions of \(1024\) instead of \(4096\). Here, we have passed the inputs through the backbone, and tokens have attended to their prior tokens. So the last token has seen all the other tokens. We store this last token as a global_vector.

Code
question_vectors = torch.stack(
    [
        model.head._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,
)
(
    question_vectors.shape,
    type_ids,
    [question.question_span for question in record.questions],
)
(torch.Size([2, 4096]), tensor([1, 0]), [(86, 92), (174, 185)])

Above, we simply take the mean of the hidden states for each question span. What is this question span? It is the start and end indices of the question in the input_ids. So for example, for the first question, the start and end indices are 86 and 92 respectively. So the question span is 86:92.

question_vectors represent the processed mean pooled hidden states for each question.

Let’s decode the input_ids at those spans to confirm. Let’s do this for both questions.

Code
(
    processor.tokenizer.decode(input_ids[batch_index, 86:92]),
    processor.tokenizer.decode(input_ids[batch_index, 174:185]),
)
('What is the invoice status?', 'Is the total above 1000 USD?')

Great! Our question spans are working correctly. We get the questions What is the invoice status? and Is the total above 1000 USD? as expected.

Now, let’s look at the next part of the forward pass.

Code
option_contexts: list[torch.Tensor] = []
lexical_options: list[torch.Tensor] = []
option_counts = []
for question in record.questions:
    context_vectors = torch.stack(
        [model.head._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))

record.questions, processor.tokenizer.decode(input_ids[0, 103:114])
((EncodedQuestion(question_id='status', question_type=1, question_span=(86, 92), option_spans=((103, 114), (120, 134), (140, 152)), option_ids=('draft', 'overdue', 'paid')),
  EncodedQuestion(question_id='large', question_type=0, question_span=(174, 185), option_spans=((196, 214), (220, 238)), option_ids=('true', 'false'))),
 '{"description":"Not sent.","option_id":"draft"}')

Let’s understand everything going on in a bit more detail.

context_vectors is taking the span of each option and taking the mean of the hidden states for that option. So for example, for the first option (draft) of the first question, the option span is 103:114, so its context vector is the mean of the hidden states for tokens 103:114. It represents processed intermediate outputs from the backbone.

What about lexical vectors? Note that it takes output_embedding_weight[token_ids].mean(dim=0) - which means it is taking the mean of output embedding vectors for each token in the option span. It represents the lexical information of the options averaged as a single vector.

So now, we have looked at the first part of the forward pass. We created context_vectors and lexical_vectors.

The context_vectors are from the hidden state - which is the last_hidden_state, representing processed tokens that have gone through all the layers of the backbone and attended to prior tokens.

lexical_vectors are the mean of all tokens in each option - including description and option value, where the vectors are taken from the output embedding matrix, thereby representing some sort of meaning or “lexicon”.

Let’s look at the next part of the forward pass where we will create option_queries, and routed_options and split_options. Let me explain each in the next section.

4.2 Step 2 - Creating query vectors per option option_queries

Code
len(option_contexts), len(lexical_options), [x.shape for x in option_contexts]
(2, 2, [torch.Size([3, 4096]), torch.Size([2, 4096])])

Can you guess why the length of option_contexts and lexical_options is 2? Because we have 2 questions that were asked. Now, since each question can have a different number of options, how do you ensure consistent tensor shapes that get passed to the next layer?

This is where option_queries that we will look at next come into the picture. For every option of a question, we create a query vector that combines its processed context, its lexical information, and its parent question vector. As a result, all three signals are added together into a single 1024-dim query vector per option ([3, 1024] for Question 1, [2, 1024] for Question 2).

Code
option_queries = []
for question_index, (context_vectors, lexical) in enumerate(
    zip(option_contexts, lexical_options)
):
    option_queries.append(
        model.head.option_context_projection(context_vectors)
        + model.head.option_lexical_projection(lexical)
        + model.head.option_question_projection(
            question_vectors[question_index]
        ).unsqueeze(0)
    )
routed_options = torch.cat(option_queries, dim=0).unsqueeze(0)

Now would be a good time to guess the shape of routed_options. Do you want to take a moment to pause and guess?

Code
(
    routed_options.shape,
    [len(option) for option in option_queries],
    option_queries[0].shape,
)
(torch.Size([1, 5, 1024]), [3, 2], torch.Size([3, 1024]))

In routed options all questions and options are combined together. But since we already had the option_counts list, we can split the routed_options back into the original questions and options.

Now coming to the shape - each option is represented by a vector of size \(1024\) which contains all information relevant to that option including the question, that this option is part of.

Therefore, forming the perfect query vector that can now attend to the whole context.

Code
for layer in model.head.evidence_layers:
    routed_options = layer(routed_options, memory)
routed_options = routed_options[0]
split_options = list(torch.split(routed_options, option_counts, dim=0))
len(split_options), len(split_options[0]), split_options[0].shape
(2, 3, torch.Size([3, 1024]))

In routed_options, to save on computation, the head attended to the whole context at once, and then split the options back into the original questions and options. This is why we saved the option_counts list.

One thing you would be wondering - “What is this evidence_layer?”. Let’s take a look!

Code
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))


evidence_layers = torch.nn.ModuleList(
    [
        EvidenceRoutingLayer(
            width=1024,
            heads=16,
            feedforward=4096,
            dropout=0.0,
        )
        for _ in range(2)
    ]
)
evidence_layers
ModuleList(
  (0-1): 2 x EvidenceRoutingLayer(
    (query_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (memory_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (attention): MultiheadAttention(
      (out_proj): NonDynamicallyQuantizableLinear(in_features=1024, out_features=1024, bias=True)
    )
    (attention_dropout): Dropout(p=0.0, inplace=False)
    (feedforward_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (feedforward): Sequential(
      (0): Linear(in_features=1024, out_features=4096, bias=True)
      (1): GELU(approximate='none')
      (2): Dropout(p=0.0, inplace=False)
      (3): Linear(in_features=4096, out_features=1024, bias=True)
      (4): Dropout(p=0.0, inplace=False)
    )
  )
)

Look closely at the forward pass for EvidenceRoutingLayer -

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))

It takes the query which is the \(1024\) vector representation of question and options, and it accepts memory which is of shape - \([1, 260, 1024]\), representing the processed context from the backbone. And it performs attention operation to attend to the memory.

The torch.nn.MultiheadAttention represents the attention layer as it was first described in the Attention Is All You Need paper (Vaswani et al. 2017). So as a result - every query, has now attended to the complete memory to collect evidence helpful in answering the question. Since, the query vectors attend to memory, this is “Cross Attention”.

Vaswani, Ashish, Noam Shazeer, Niki Parmar, et al. 2017. “Attention Is All You Need.” CoRR abs/1706.03762. http://arxiv.org/abs/1706.03762.

To summarise, until now, we have split options again - which is a single vector of size \(1024\) per option, that has attended to the whole context, and therefore found any evidence from state, question to reach closer to the answer.

We still need to convert the vectors to probabilities. Let’s look at the next section of the forward pass where we combine questions, and their respective options into a single vector and perform cross-attention to memory again.

4.3 Step 3 - Combine questions and options into a single vector and cross-attend to memory

Code
base_fields = model.head.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)
    )
option_summaries[0].shape, option_summaries[1].shape, split_options[0].shape, split_options[1].shape
(torch.Size([1024]),
 torch.Size([1024]),
 torch.Size([3, 1024]),
 torch.Size([2, 1024]))

Can you describe what is happening above?

First - we take the question_vectors, which as explained in Section 4.1, represent the processed mean pooled hidden states for each question. We project them to a lower dimension, from 4096 to 1024, and call it base_fields. (BTW, the naming of variables is something that can be worked upon but I am sticking to the same naming to match the complete source code)

Next, split_options[0] of shape \([3, 1024]\) performs a dot product with field to return weights per option giving higher weights to the most relevant options.

One intuition I did have while writing this blog post - is that routing_weights would converge to the right options by giving them higher weights. Let’s see if this hypothesis is True!

Code
routing_weights
tensor([1., 0.], dtype=torch.bfloat16, grad_fn=<SoftmaxBackward0>)

Looking at the second question, the routing_weights have given full weightage to the first option! Which was a representation of “Yes” to the question “Is the total above 1000 USD?”.

I hope this helps my reader to build an intuition for how decision models are working under the hood! (As it did for me)

Code
fields = (
    base_fields
    + model.head.option_summary_norm(torch.stack(option_summaries))
    + model.head.global_projection(global_vector).unsqueeze(0)
    + model.head.type_embedding(type_ids)
)
fields = fields.unsqueeze(0 )
fields.shape
torch.Size([1, 2, 1024])

Finally, every question and its respective options are combined by summing four vectors: base_fields (the projected question vectors), option_summaries (which we just saw already concentrates weight on the right option), global_vector (the last token from the backbone), and the embedding for the question type_ids.

Interesting right? Why pass fields through another stack of Transformer layers next? Notice the key difference in model.head.layers below: unlike EvidenceRoutingLayer (cross-attention only), each TransformerDecoderLayer has a self_attn layer first - letting Field 1 (status) and Field 2 (large) finally attend to each other jointly - followed by multihead_attn to re-check memory!

Code
model.head.layers
ModuleList(
  (0-3): 4 x TransformerDecoderLayer(
    (self_attn): MultiheadAttention(
      (out_proj): NonDynamicallyQuantizableLinear(in_features=1024, out_features=1024, bias=True)
    )
    (multihead_attn): MultiheadAttention(
      (out_proj): NonDynamicallyQuantizableLinear(in_features=1024, out_features=1024, bias=True)
    )
    (linear1): Linear(in_features=1024, out_features=4096, bias=True)
    (dropout): Dropout(p=0.0, inplace=False)
    (linear2): Linear(in_features=4096, out_features=1024, bias=True)
    (norm1): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (norm2): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (norm3): LayerNorm((1024,), eps=1e-05, elementwise_affine=True, bias=True)
    (dropout1): Dropout(p=0.0, inplace=False)
    (dropout2): Dropout(p=0.0, inplace=False)
    (dropout3): Dropout(p=0.0, inplace=False)
  )
)
Code
for layer in model.head.layers:
    fields = layer(fields, memory)
fields = model.head.field_norm(fields[0])
fields.shape, fields[0].shape
(torch.Size([2, 1024]), torch.Size([1024]))

Next step is to pass fields through the 4 TransformerDecoderLayers, drop the batch dimension with fields[0] ([1, 2, 1024] → [2, 1024], undoing the unsqueeze), and apply field_norm across both fields. Because option_summaries were already folded into fields, running unmasked self_attn inside these layers means Question 1 (status) can finally see Question 2 (large) and its tentative answer, and vice versa - and then cross-attend back to memory before finalizing. BTW, as part of writing this blog post - I see opportunities on where the codebase could be made tidier :)

Let’s move on to the next step and convert fields to logits.

4.4 Step 4 - Convert fields to logits

So by now we have fields which hold the final vector for each question, which has seen full context (memory) and other questions, their tentative answers. We finally need to convert this fields to logits per option per question.

Code
record.questions, fields[0].shape, fields[1].shape, lexical_options[0].shape, split_options[0].shape
((EncodedQuestion(question_id='status', question_type=1, question_span=(86, 92), option_spans=((103, 114), (120, 134), (140, 152)), option_ids=('draft', 'overdue', 'paid')),
  EncodedQuestion(question_id='large', question_type=0, question_span=(174, 185), option_spans=((196, 214), (220, 238)), option_ids=('true', 'false'))),
 torch.Size([1024]),
 torch.Size([1024]),
 torch.Size([3, 4096]),
 torch.Size([3, 1024]))

Rather than going through the for loop, let’s just see how Clef gets the logits for the first question which was “What is the invoice status?” with options paid, overdue and draft.

Code
record_logits: list[torch.Tensor] = []
field = fields[0]
question = record.questions[0]
lexical = lexical_options[0]
routed = split_options[0]
field.shape, lexical.shape, routed.shape
(torch.Size([1024]), torch.Size([3, 4096]), torch.Size([3, 1024]))

Below, Clef first creates anchor by adding the first question’s question_vectors[0] and global_vector, then L2-normalizing it to unit length. Similarly, lexical_anchor L2-normalizes the 3 static lm_head option vectors (draft, overdue, paid).

Code
anchor = functional.normalize(
    question_vectors[len(record_logits)] + global_vector,
        dim=-1,
    )
lexical_anchor = functional.normalize(lexical, dim=-1)
anchor.shape, lexical_anchor.shape, global_vector.shape, question_vectors[0].shape
(torch.Size([4096]),
 torch.Size([3, 4096]),
 torch.Size([4096]),
 torch.Size([4096]))
Code
prior_scale = model.head.prior_logit_scale.clamp(max=math.log(100.0)).exp()
prior = prior_scale * torch.matmul(lexical_anchor, anchor)
prior_scale, prior, torch.matmul(lexical_anchor, anchor)
(tensor(9.9375, dtype=torch.bfloat16, grad_fn=<ExpBackward0>),
 tensor([0.0679, 0.9648, 0.5977], dtype=torch.bfloat16, grad_fn=<MulBackward0>),
 tensor([0.0068, 0.0972, 0.0601], dtype=torch.bfloat16, grad_fn=<MvBackward0>))

Since both lexical_anchor ([3, 4096]) and anchor ([4096]) are L2-normalized, torch.matmul(lexical_anchor, anchor) is simply their cosine similarity (3 numbers in [-1, 1]).

NoteWhy L2-normalize + matmul equals cosine similarity

For any two vectors \(a\) and \(b\), the L2 norm is simply Euclidean length:

\[\|a\|_2 = \sqrt{a_1^2 + a_2^2 + \dots + a_d^2}\]

functional.normalize(a, dim=-1) divides \(a\) by its own length to produce a unit vector \(\hat{a} = a / \|a\|_2\) with \(\|\hat{a}\|_2 = 1\). Plugging two unit vectors \(\hat{a}\) and \(\hat{b}\) into the cosine similarity formula makes the denominator \(1 \times 1 = 1\):

\[\cos(\theta) = \frac{\hat{a} \cdot \hat{b}}{\|\hat{a}\|_2 \|\hat{b}\|_2} = \hat{a} \cdot \hat{b}\]

So torch.matmul(lexical_anchor, anchor) computes the exact cosine similarity for all 3 options in one matrix multiply.

Next question you might ask - Why multiply by prior_scale? Think of prior_scale as a volume knob - a single learned scalar by the head (self.prior_logit_scale = nn.Parameter(torch.zeros(()))) that increases the gap between the cosine similarities before softmax.

Let’s look at the impact of this value and output softmax values:

Multiplier (prior_scale) Scaled Logits After softmax
1 (no scaling) [0.007, 0.097, 0.060] [0.318, 0.348, 0.335] (almost flat - looks random!)
9.9375 (what Clef learned) [0.068, 0.965, 0.598] [0.194, 0.476, 0.330] (overdue has highest value)
50 (if turned higher) [0.340, 4.860, 3.005] [0.009, 0.857, 0.134] (much sharper and easier to distinguish)

And why .clamp(max=math.log(100.0)).exp() instead of learning a raw multiplier directly? Borrowing the exact trick from CLIP (Radford et al. 2021) (which I also covered in my Understanding CLIP post), storing the parameter in log space guarantees .exp() is always strictly positive (never flipping the ranking), while clamping at log(100) caps the multiplier at 100 so training doesn’t explode or turn softmax wildly overconfident. Here, Clef learned prior_logit_scale ≈ 2.296, giving prior_scale = 9.9375 and a ~48% baseline confidence on overdue.

Radford, Alec, Jong Wook Kim, Chris Hallacy, et al. 2021. “Learning Transferable Visual Models from Natural Language Supervision.” CoRR abs/2103.00020. https://arxiv.org/abs/2103.00020.

But wait, Aman, you mentioned at the start of the blog post that the output probability for “overdue” is 97.3%? Let’s see how!

Code
options = model.head.option_norm(routed)
repeated_field = field.unsqueeze(0).expand_as(options)
cosine = functional.cosine_similarity(repeated_field, options, dim=-1)
options.shape, repeated_field.shape, cosine
(torch.Size([3, 1024]),
 torch.Size([3, 1024]),
 tensor([-0.2471, -0.0693, -0.2598], dtype=torch.bfloat16,
        grad_fn=<SumBackward1>))

Now we switch to the 1024-dim vectors we built in Section 4.2 and Section 4.3:

  • options = model.head.option_norm(routed) applies LayerNorm to our 3 evidence-routed options ([3, 1024]) so they live on the same scale as field (which already went through field_norm).
  • repeated_field = field.unsqueeze(0).expand_as(options) broadcasts the single [1024] field vector 3 times into [3, 1024] so each row lines up side-by-side with draft, overdue, and paid.
  • cosine computes the row-by-row cosine similarity ([3]) between the decided field and each evidence-routed option.
Code
features = torch.cat(
    [
        repeated_field,
        options,
        repeated_field * options,
        torch.abs(repeated_field - options),
    ],
    dim=-1,
)
residual = model.head.residual_scorer(features).squeeze(-1)
features.shape, residual
(torch.Size([3, 4096]),
 tensor([-41.2500, -11.7500, -40.5000], dtype=torch.bfloat16,
        grad_fn=<SqueezeBackward1>))

Cosine similarity is a single unweighted dot product across all 1024 dimensions - it only checks whether field and option point in the same direction, which can be rigid for asymmetric or conditional choices (like picking false, none of the above, or distinguishing adjacent rubric scores).

To go beyond plain angle similarity, Clef borrows the classic InferSent (Conneau et al. 2017) pair-interaction trick: for each (field, option) pair (u, v), concatenate [u, v, u * v, |u - v|] along the last dimension (1024 x 4 = 4096) to let the network weight individual dimensions (u * v), spot explicit mismatches (|u - v|), and learn non-linear cross-dimension interactions. Passing features ([3, 4096]) through the 2-layer GELU MLP residual_scorer (4096 -> 1024 -> 1) produces one non-linear score per option (residual, shape [3]). Look at the output above ([-41.25, -11.75, -40.50]) - the MLP creates a ~30-point separation in favor of overdue!

Conneau, Alexis, Douwe Kiela, Holger Schwenk, Loïc Barrault, and Antoine Bordes. 2017. “Supervised Learning of Universal Sentence Representations from Natural Language Inference Data.” Proceedings of the 2017 Conference on Empirical Methods in Natural Language Processing (EMNLP). https://arxiv.org/abs/1705.02364.
Code
joint_scale = model.head.joint_logit_scale.clamp(max=math.log(100.0)).exp()
joint = joint_scale * cosine + residual
final_logits = prior + torch.sigmoid(model.head.residual_gate) * joint
joint_scale, torch.sigmoid(model.head.residual_gate), final_logits, final_logits.float().softmax(-1)
(tensor(9.9375, dtype=torch.bfloat16, grad_fn=<ExpBackward0>),
 tensor(0.1191, dtype=torch.bfloat16, grad_fn=<SigmoidBackward0>),
 tensor([-5.1562, -0.5195, -4.5312], dtype=torch.bfloat16,
        grad_fn=<AddBackward0>),
 tensor([0.0094, 0.9730, 0.0176], grad_fn=<SoftmaxBackward0>))

Finally, we combine everything:

  1. Scale the head’s cosine by joint_scale (the exact same learned CLIP volume knob as prior_scale) and add the MLP residual to get joint.
  2. Blend the 4096-dim Qwen skip connection (prior) with the 1024-dim head score (joint) via a single learned scalar gate torch.sigmoid(model.head.residual_gate).
  3. Apply .softmax(-1) to final_logits ([-5.1562, -0.5195, -4.5312]) - and out come [0.0094, 0.9730, 0.0176], landing right back on overdue = 0.973 from the very first cell of this post!

Running the exact same loop for Question 2 (large) produces 0.9734 for true - all in a single forward pass without producing any output tokens!

5 Conclusion

As part of this blog post, we walked through the complete model architecture of Cloudflare’s Clef (Cloudflare 2026) - from raw JSON state and questions, through encode_record and the Qwen backbone ([1, 260, 4096]), and step-by-step through every tensor inside JointSchemaHead and EvidenceRoutingLayer all the way to the exact 0.973 and 0.9734 probabilities returned by systemone.

Cloudflare. 2026. “Clef: Multimodal Decision Models.” https://huggingface.co/Cloudflare/clef.

Before we wrap up, let’s revisit the 6 questions we started with at the top of this post:

  1. How is it different from standard classification? There is no fixed Linear(d, num_classes) head. Every option is encoded dynamically from its own text span (both contextual hidden states and static lm_head output embeddings) and scored against its field representation.
  2. How is every question processed in one forward pass? The backbone runs a single prefill pass over the full state and schema (no autoregressive token generation), and JointSchemaHead scores all questions and options in parallel using cross-attention to memory and self-attention across fields.
  3. Can each question have a different number of options? Yes. Options are pooled per question into variable-length tensors ([3, 4096] and [2, 4096]), concatenated into one flat query tensor ([1, 5, 1024]) for EvidenceRoutingLayer, split back using option_counts = [3, 2], and collapsed via attention pooling (option_summaries).
  4. What is the context limit of state and questions? They share one joint max_length (default 16384 in encode_record, up to the backbone’s context window).
  5. Does ordering of options or fields impact the probability? Yes, they might. For choice fields, question_options() sorts option keys alphabetically (draft, overdue, paid), making JSON key order deterministic. However, because the Qwen backbone is strictly causal, later questions and options attend to earlier ones while earlier ones cannot see later ones until EvidenceRoutingLayer and TransformerDecoderLayer run.
  6. Are decision models deterministic? Yes - there is no sampling loop (temperature or top_p token draws), just one deterministic forward pass followed by softmax.

We still haven’t covered how Clef (and other open-weight decision models) are trained - including LoRA adaptation, Brier loss calibration, and how architectures like mammoth-1, pplx-decider, and GLiDE tackle the same problem differently (such as switching full-attention layers to block-bidirectional attention instead of relying on a separate decoder head).

I hope this notebook helps you look past the API and build real intuition for how Decision Models work under the hood. In the next post, we will look at how other open-weight decision models are architected and might also work towards training our own high-performing model on the public Decision Index.

Subscribe to Aman Arora's blog:

* indicates required

Citation

BibTeX citation:
@online{arora2026,
  author = {Arora, Aman},
  title = {Deep Dive into {CLEF} with Step by Step Walkthrough of Its
    Model Architecture in {PyTorch}},
  date = {2026-11-25},
  url = {https://amaarora.github.io/posts/2026-25-11-deepdive-into-clef.html},
  langid = {en}
}
For attribution, please cite this work as:
Arora, Aman. 2026. “Deep Dive into CLEF with Step by Step Walkthrough of Its Model Architecture in PyTorch.” Aman Arora’s Blog, November 25. https://amaarora.github.io/posts/2026-25-11-deepdive-into-clef.html.