Run this model with HF Jobs

Run CloudGoat/Samothrace-4B-Preview on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/CloudGoat/Samothrace-4B-Preview. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/CloudGoat/Samothrace-4B-Preview on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/CloudGoat/Samothrace-4B-Preview. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/CloudGoat/Samothrace-4B-Preview. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 12,564 Bytes
254b3ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Samothrace: looped Qwen3.5 with per-step LoRA and per-step gated scaling.

Layout (Qwen3.5-4B, 32 layers = 8 x [DeltaNet x3 + Attn x1]):
    prelude = layers [0, core_start)            run once, frozen
    core    = layers [core_start, core_end)     run K times
    coda    = layers [core_end, 32)             run once, frozen

Step 1 of the core is the original layer stack (no adapter), so with a_k = 0
the model is bit-identical to the base model for every K.
Step k >= 2:  h <- h + a_k * (Core(h; W + dW_k) - h),   a_k in R^hidden, init 0.

Memory tricks (training):
  * prelude + core step 1 contain no trainable params -> run under no_grad,
    no activations kept.
  * steps 2..K and coda run with per-layer activation checkpointing.
  * per-step LoRA lives in one module per Linear (stacked A/B), no peft.
  * the LM head + CE is computed in chunks (vocab is 248k), see losses.py.
"""
from __future__ import annotations

import copy
import math
from dataclasses import dataclass, field

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint


# ---- memory-bounded attention (T4: no flash-attn, head_dim 256 -> SDPA falls back to math) ----
ATTN_QCHUNK = 512


def _attn_chunk(q, k, v, m, qs, scaling):
    # q [B,H,c,D] = query positions qs..qs+c-1 (absolute); k,v [B,H,qs+c,D]; m: 4D mask slice or None (causal)
    if m is None:
        c, Tk = q.shape[2], k.shape[2]
        m = torch.arange(Tk, device=q.device)[None, :] <= torch.arange(qs, qs + c, device=q.device)[:, None]
    return F.scaled_dot_product_attention(q, k, v, attn_mask=m, scale=scaling)


def chunked_causal_attention(module, query, key, value, attention_mask, dropout=0.0, scaling=None, **kwargs):
    """Causal attention in query chunks; each chunk is checkpointed when grads are on, so peak memory is
    O(chunk * T) instead of O(T^2) in forward and backward. Short / decode calls go to plain SDPA."""
    from transformers.integrations.sdpa_attention import sdpa_attention_forward
    B, H, Tq, D = query.shape
    Tk = key.shape[2]
    if Tq <= ATTN_QCHUNK:
        return sdpa_attention_forward(module, query, key, value, attention_mask, dropout=dropout, scaling=scaling, **kwargs)
    rep = H // key.shape[1]
    if rep > 1:
        key = key.repeat_interleave(rep, dim=1)
        value = value.repeat_interleave(rep, dim=1)
    off = Tk - Tq                                 # cached past length
    m4 = attention_mask if (attention_mask is not None and attention_mask.dim() == 4) else None
    grad = torch.is_grad_enabled() and (query.requires_grad or key.requires_grad or value.requires_grad)
    outs = []
    for s in range(0, Tq, ATTN_QCHUNK):
        e = min(s + ATTN_QCHUNK, Tq)
        mc = None if m4 is None else m4[:, :, s:e, :off + e]
        args = (query[:, :, s:e], key[:, :, :off + e], value[:, :, :off + e], mc, off + s, scaling)
        outs.append(checkpoint(_attn_chunk, *args, use_reentrant=False) if grad else _attn_chunk(*args))
    return torch.cat(outs, 2).transpose(1, 2).contiguous(), None


def register_chunked_attention(name="samo_chunked"):
    from transformers import AttentionInterface
    from transformers.masking_utils import AttentionMaskInterface, sdpa_mask
    AttentionInterface.register(name, chunked_causal_attention)
    AttentionMaskInterface.register(name, sdpa_mask)
    return name


@dataclass
class LoopConfig:
    core_start: int = 8
    core_end: int = 20
    max_steps: int = 3                 # K_max (step 1 = original pass)
    lora_r: int = 16
    lora_alpha: int = 32
    lora_dropout: float = 0.0
    targets: tuple = (
        # full attention
        "q_proj", "k_proj", "v_proj", "o_proj",
        # gated deltanet
        "in_proj_qkv", "in_proj_z", "out_proj",
        # mlp
        "gate_proj", "up_proj", "down_proj",
    )
    gate_init: float = 0.0             # a_k init
    checkpoint_layers: bool = True


class StepState:
    """Shared mutable 'which loop step is running' flag (0 = no adapter)."""
    def __init__(self):
        self.step = 0


class MultiStepLoRALinear(nn.Module):
    """y = W x + (alpha/r) * B_s A_s x for the active step s (s >= 1)."""

    def __init__(self, base: nn.Linear, n_steps: int, r: int, alpha: int,
                 state: StepState, dropout: float = 0.0):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad_(False)
        self.state = state
        self.r, self.scale = r, alpha / r
        dev = base.weight.device
        # fp32 master params; cast to activation dtype at use
        self.lora_A = nn.Parameter(torch.empty(n_steps, r, base.in_features, device=dev, dtype=torch.float32))
        self.lora_B = nn.Parameter(torch.zeros(n_steps, base.out_features, r, device=dev, dtype=torch.float32))
        for s in range(n_steps):
            nn.init.kaiming_uniform_(self.lora_A[s], a=math.sqrt(5))
        self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity()

    @property
    def weight(self):  # some HF code peeks at .weight
        return self.base.weight

    def forward(self, x):
        y = self.base(x)
        s = self.state.step
        if s <= 0:
            return y
        A = self.lora_A[s - 1].to(x.dtype)
        B = self.lora_B[s - 1].to(x.dtype)
        return y + (self.drop(x) @ A.t() @ B.t()) * self.scale


def _wrap_linears(module: nn.Module, cfg: LoopConfig, state: StepState):
    n_adapt = cfg.max_steps - 1
    for name, child in list(module.named_children()):
        if isinstance(child, nn.Linear) and name in cfg.targets:
            setattr(module, name, MultiStepLoRALinear(child, n_adapt, cfg.lora_r, cfg.lora_alpha, state, cfg.lora_dropout))
        else:
            _wrap_linears(child, cfg, state)


class Samothrace(nn.Module):
    def __init__(self, causal_lm: nn.Module, cfg: LoopConfig):
        super().__init__()
        self.lm = causal_lm
        self.cfg = cfg
        tm = causal_lm.model                                  # Qwen3_5TextModel
        self.tcfg = tm.config
        L = self.tcfg.num_hidden_layers
        assert 0 < cfg.core_start < cfg.core_end < L
        for p in causal_lm.parameters():
            p.requires_grad_(False)
        self.state = StepState()
        for i in range(cfg.core_start, cfg.core_end):
            _wrap_linears(tm.layers[i], cfg, self.state)
        H = self.tcfg.hidden_size
        dev = tm.embed_tokens.weight.device
        self.gates = nn.Parameter(torch.full((cfg.max_steps - 1, H), cfg.gate_init, device=dev, dtype=torch.float32))
        self.n_core = cfg.core_end - cfg.core_start
        self._orig_idx = {i: self._get_idx(tm.layers[i]) for i in range(cfg.core_start, cfg.core_end)}

    # ---- helpers -----------------------------------------------------------
    @staticmethod
    def _mixer(layer):
        return layer.linear_attn if getattr(layer, "block_type", getattr(layer, "layer_type", None)) == "linear_attention" else layer.self_attn

    def _get_idx(self, layer):
        return self._mixer(layer).layer_idx

    def _set_idx(self, layer, idx):
        self._mixer(layer).layer_idx = idx
        if hasattr(layer, "layer_idx"):
            layer.layer_idx = idx

    def virtual_idx(self, layer_i: int, step: int) -> int:
        """Cache slot of core layer `layer_i` at loop step `step` (1-based)."""
        if step == 1:
            return layer_i
        L = self.tcfg.num_hidden_layers
        return L + (step - 2) * self.n_core + (layer_i - self.cfg.core_start)

    def cache_config(self, K: int):
        """Text config whose layer list covers every (layer, step) cache slot."""
        c = copy.deepcopy(self.tcfg)
        L = c.num_hidden_layers
        extra = [c.layer_types[i] for _ in range(K - 1) for i in range(self.cfg.core_start, self.cfg.core_end)]
        c.layer_types = list(c.layer_types) + extra
        c.num_hidden_layers = L + len(extra)
        return c

    def new_cache(self, K: int):
        from transformers import DynamicCache
        return DynamicCache(config=self.cache_config(K))

    def trainable_parameters(self):
        return [p for p in self.parameters() if p.requires_grad]

    # ---- forward -----------------------------------------------------------
    def _run_layer(self, layer, h, ctx, ckpt, step=0, vidx=None):
        # step / cache slot are bound here so checkpoint recomputation sees the same config
        def f(x):
            prev_step, prev_idx = self.state.step, self._get_idx(layer)
            self.state.step = step
            if vidx is not None:
                self._set_idx(layer, vidx)
            try:
                return layer(x, **ctx)
            finally:
                self.state.step = prev_step
                self._set_idx(layer, prev_idx)
        if ckpt and self.training and torch.is_grad_enabled():
            return checkpoint(f, h, use_reentrant=False)
        return f(h)

    def _setup(self, input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds):
        from transformers.masking_utils import create_causal_mask
        try:
            from transformers.masking_utils import create_recurrent_attention_mask
        except ImportError:
            create_recurrent_attention_mask = None
        tm = self.lm.model
        if inputs_embeds is None:
            inputs_embeds = tm.embed_tokens(input_ids)
        B, T, _ = inputs_embeds.shape
        if position_ids is None:
            past = cache.get_seq_length() if cache is not None else 0
            position_ids = torch.arange(T, device=inputs_embeds.device)[None].expand(B, -1) + past
        text_pos = position_ids
        mrope_pos = position_ids[None].expand(3, B, -1)
        mk = dict(config=self.tcfg, inputs_embeds=inputs_embeds, attention_mask=attention_mask,
                  cache=cache, position_ids=text_pos)
        masks = {"full_attention": create_causal_mask(**mk)}
        masks["linear_attention"] = create_recurrent_attention_mask(**mk) if create_recurrent_attention_mask else attention_mask
        pos_emb = tm.rotary_emb(inputs_embeds, mrope_pos)

        def ctx(i):
            return dict(position_embeddings=pos_emb, attention_mask=masks[self.tcfg.layer_types[i]],
                        position_ids=text_pos, cache=cache, use_cache=use_cache)
        return inputs_embeds, ctx

    def prefix(self, input_ids=None, attention_mask=None, position_ids=None, cache=None, use_cache=False,
               inputs_embeds=None):
        """Prelude + core step 1 (frozen, no adapter). Returns (h, ctx). In training this runs without a graph."""
        h, ctx = self._setup(input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds)
        self.state.step = 0
        with torch.set_grad_enabled(torch.is_grad_enabled() and not self.training):
            for i in range(0, self.cfg.core_end):
                h = self.lm.model.layers[i](h, **ctx(i))
        h = h.detach() if self.training else h
        return h, ctx

    def from_prefix(self, h, ctx, K: int):
        """Loop steps 2..K + coda + final norm, starting from prefix() output."""
        cfg, tm = self.cfg, self.lm.model
        assert 1 <= K <= cfg.max_steps
        ck = cfg.checkpoint_layers
        for k in range(2, K + 1):
            h_in = h
            for i in range(cfg.core_start, cfg.core_end):
                h = self._run_layer(tm.layers[i], h, ctx(i), ck, step=k - 1, vidx=self.virtual_idx(i, k))
            g = self.gates[k - 2].to(h.dtype)
            h = h_in + g * (h - h_in)
        for i in range(cfg.core_end, self.tcfg.num_hidden_layers):
            h = self._run_layer(tm.layers[i], h, ctx(i), ck)
        return tm.norm(h)

    def hidden(self, input_ids=None, K: int = None, attention_mask=None, position_ids=None,
               cache=None, use_cache=False, inputs_embeds=None):
        """Returns final-normed hidden states [B, T, H]."""
        K = K or self.cfg.max_steps
        h, ctx = self.prefix(input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds)
        return self.from_prefix(h, ctx, K)

    def forward(self, input_ids=None, K=None, **kw):
        h = self.hidden(input_ids, K, **kw)
        return self.lm.lm_head(h)

    # ---- save / load adapters ---------------------------------------------
    def adapter_state_dict(self):
        return {n: p.detach().cpu() for n, p in self.named_parameters() if p.requires_grad}

    def load_adapter_state_dict(self, sd):
        missing = self.load_state_dict(sd, strict=False)
        return missing