Run this model with HF Jobs

Run webbrain-one/WebBrain-LingLoop-8B-A1.3B-MLX-4bit 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 to fine-tune https://huggingface.co/webbrain-one/WebBrain-LingLoop-8B-A1.3B-MLX-4bit. 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/webbrain-one/WebBrain-LingLoop-8B-A1.3B-MLX-4bit 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/webbrain-one/WebBrain-LingLoop-8B-A1.3B-MLX-4bit. 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.
File size: 6,965 Bytes
9cf4ddf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MLX-LM architecture for the published WebBrain LingLoop checkpoint.

The base decoder and checkpoint transforms come from MLX-LM's Bailing V3.
The loop follows the publisher's LoopedBailingMoeV3ForCausalLM implementation
at https://huggingface.co/webbrain-one/WebBrain-LingLoop-8B-A1.3B/blob/6cd99926f92814c991585f48254dbd172cd8d162/looped_ling3.py.
This module is self-contained so it can accompany a converted checkpoint.
"""

import math
from dataclasses import dataclass

import mlx.core as mx
import mlx.nn as nn
from mlx_lm.models import bailing_moe_v3
from mlx_lm.models.base import create_attention_mask, create_ssm_mask
from mlx_lm.models.cache import ArraysCache, KVCache


@dataclass
class ModelArgs(bailing_moe_v3.ModelArgs):
    loop_core_start: int = 4
    loop_core_end: int = 20
    loop_num_passes: int = 2
    loop_gate_rank: int = 64


def _rms_norm_fp32(x):
    x = x.astype(mx.float32)
    return x * mx.rsqrt(mx.mean(mx.square(x), axis=-1, keepdims=True) + 1e-6)


class DepthAttentionReader(nn.Module):
    def __init__(self, hidden_size):
        super().__init__()
        self.q = mx.zeros((hidden_size,), dtype=mx.float32)
        self.scale = 1.0 / math.sqrt(hidden_size)

    def __call__(self, previous_states, dtype):
        scores = mx.sum(_rms_norm_fp32(previous_states) * self.q, axis=-1) * self.scale
        weights = mx.softmax(scores, axis=-1)
        message = mx.sum(weights[..., None] * previous_states.astype(mx.float32), axis=-2)
        return message.astype(dtype)


class CrossPassGate(nn.Module):
    def __init__(self, hidden_size, rank):
        super().__init__()
        self.w_down = nn.Linear(hidden_size * 2, rank, bias=False)
        self.w_forget = nn.Linear(rank, hidden_size, bias=False)
        self.w_gain = nn.Linear(rank, hidden_size, bias=False)
        self.w_forget.weight = mx.zeros((hidden_size, rank), dtype=mx.float32)
        self.w_gain.weight = mx.zeros((hidden_size, rank), dtype=mx.float32)

    def __call__(self, x, message):
        inputs = mx.concatenate((_rms_norm_fp32(x), _rms_norm_fp32(message)), axis=-1)
        state = self.w_down(inputs)
        forget = mx.tanh(self.w_forget(state))
        gain = mx.tanh(self.w_gain(state))
        delta = -forget * x.astype(mx.float32) + gain * message.astype(mx.float32)
        return x + delta.astype(x.dtype)


class LoopAdapter(nn.Module):
    def __init__(self, num_layers, hidden_size, rank):
        super().__init__()
        self.attn_readers = [DepthAttentionReader(hidden_size) for _ in range(num_layers)]
        self.attn_gates = [CrossPassGate(hidden_size, rank) for _ in range(num_layers)]
        self.mlp_readers = [DepthAttentionReader(hidden_size) for _ in range(num_layers)]
        self.mlp_gates = [CrossPassGate(hidden_size, rank) for _ in range(num_layers)]

    def run_layer(self, index, layer, hidden, previous_states, mask, cache):
        # Each gate changes the sublayer input. The residual retains the ungated hidden state.
        message = self.attn_readers[index](previous_states, hidden.dtype)
        inputs = self.attn_gates[index](hidden, message)
        hidden = hidden + layer.attention(layer.input_layernorm(inputs), mask, cache)
        message = self.mlp_readers[index](previous_states, hidden.dtype)
        inputs = self.mlp_gates[index](hidden, message)
        return hidden + layer.mlp(layer.post_attention_layernorm(inputs))


class Model(bailing_moe_v3.Model):
    """Reuse each physical core layer across passes, with separate state slots."""

    def __init__(self, args):
        if not 0 <= args.loop_core_start < args.loop_core_end <= args.num_hidden_layers:
            raise ValueError("Invalid LingLoop core layer range")
        if args.loop_num_passes < 1 or args.loop_gate_rank < 1:
            raise ValueError("LingLoop pass count and gate rank must be positive")
        super().__init__(args)
        self._core_layers = range(args.loop_core_start, args.loop_core_end)
        self._num_slots = len(self.layers) + (args.loop_num_passes - 1) * len(self._core_layers)
        self.loop_adapter = LoopAdapter(len(self._core_layers), args.hidden_size, args.loop_gate_rank)

    def make_cache(self):
        cache = super().make_cache()
        for _ in range(1, self.args.loop_num_passes):
            for index in self._core_layers:
                cache.append(ArraysCache(size=4) if self.layers[index].is_linear else KVCache())
        return cache

    @property
    def quant_predicate(self):
        base_predicate = super().quant_predicate

        def predicate(path, module):
            return not path.startswith("loop_adapter.") and base_predicate(path, module)

        return predicate

    def __call__(self, tokens, cache=None):
        physical = self.layers
        if cache is None:
            cache = [None] * self._num_slots
        elif len(cache) != self._num_slots:
            raise ValueError(f"LingLoop requires {self._num_slots} cache slots, got {len(cache)}")

        model = self.model
        hidden = model.word_embeddings(tokens)
        # All passes see the same token positions. Compute masks before updating slots.
        attention_mask = None
        linear_mask = None
        if model.attention_index is not None:
            attention_mask = create_attention_mask(hidden, cache[model.attention_index], return_array=True)
        if model.linear_index is not None:
            linear_mask = create_ssm_mask(hidden, cache[model.linear_index])

        for index in range(self._core_layers.start):
            layer = physical[index]
            mask = linear_mask if layer.is_linear else attention_mask
            hidden = layer(hidden, mask, cache[index])
        prelude = hidden

        previous_states = None
        for pass_index in range(self.args.loop_num_passes):
            hidden = prelude
            states = []
            for core_index, index in enumerate(self._core_layers):
                layer = physical[index]
                mask = linear_mask if layer.is_linear else attention_mask
                if pass_index == 0:
                    hidden = layer(hidden, mask, cache[index])
                else:
                    slot = len(physical) + (pass_index - 1) * len(self._core_layers) + core_index
                    hidden = self.loop_adapter.run_layer(core_index, layer, hidden, previous_states, mask, cache[slot])
                if pass_index + 1 < self.args.loop_num_passes:
                    states.append(hidden)
            if states:
                previous_states = mx.stack(states, axis=-2)

        for index in range(self._core_layers.stop, len(physical)):
            layer = physical[index]
            mask = linear_mask if layer.is_linear else attention_mask
            hidden = layer(hidden, mask, cache[index])

        hidden = model.norm(hidden)
        if self.lm_head is None:
            return model.word_embeddings.as_linear(hidden)
        return self.lm_head(hidden)