File size: 10,210 Bytes
36c78b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, sys; sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from bit_transformer import (
    BitTransformerLM,
    hil_safe_inference,
    text_to_bits,
    bits_to_text,
    plot_telemetry,
    infer_long_sequence,
    diffusion_inference,
    compress_bits,
)
from bit_transformer.safety import SafetyGate
import torch
import torch.nn.functional as F
import torch.nn as nn
import pytest

def test_forward_pass():
    B, L = 2, 8
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=L)
    bits = torch.randint(0, 2, (B, L), dtype=torch.long)
    logits, telemetry = model(bits)
    assert logits.shape == (B, L, 2)
    required_keys = {
        "negentropy_input",
        "lz_complexity_input",
        "negentropy_logits",
        "lz_complexity_logits",
        "symbiosis_kl",
        "symbiosis_score",
        "attention_entropy",
        "attention_entropy_mean",
    }
    assert required_keys.issubset(telemetry.keys())
    pred = logits[:, :-1, :].reshape(-1, 2)
    target = bits[:, 1:].reshape(-1)
    loss = F.cross_entropy(pred, target)
    assert torch.isfinite(loss)


def test_autocast_forward():
    model = BitTransformerLM(
        d_model=32,
        nhead=4,
        num_layers=1,
        dim_feedforward=64,
        max_seq_len=8,
        use_autocast=True,
    )
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, _ = model(bits)
    assert logits.shape == (1, 8, 2)


def test_act_forward():
    model = BitTransformerLM(
        d_model=32,
        nhead=4,
        num_layers=2,
        dim_feedforward=64,
        max_seq_len=8,
        use_act=True,
    )
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, tele = model(bits)
    assert logits.shape == (1, 8, 2)
    assert "halt_probs" in tele


def test_act_skips_layers():
    model = BitTransformerLM(
        d_model=16,
        nhead=4,
        num_layers=3,
        dim_feedforward=32,
        max_seq_len=8,
        use_act=True,
        act_threshold=0.5,
    )
    for proj in model.halt_projs:
        nn.init.constant_(proj.weight, 0.0)
        nn.init.constant_(proj.bias, 10.0)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    _, tele = model(bits)
    assert len(tele["halt_probs"]) < model.num_layers


def test_hil_safety_gate():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    # Expect gate triggered with high floors
    raised = False
    try:
        hil_safe_inference(model, bits, c_floor=1.0, s_floor=1.0)
    except RuntimeError:
        raised = True
    assert raised


def test_hil_safety_non_strict():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    out, _ = hil_safe_inference(model, bits, c_floor=1.0, s_floor=1.0, strict=False)
    assert out.shape == bits.shape


def test_safety_gate_burn_in():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    gate = SafetyGate(c_floor=1.0, s_floor=1.0, burn_in=1)
    hil_safe_inference(model, bits, gate=gate)
    with pytest.raises(RuntimeError):
        hil_safe_inference(model, bits, gate=gate)


def test_bit_io_roundtrip():
    text = "hello"
    bits = text_to_bits(text)
    assert bits_to_text(bits) == text


def test_plot_telemetry():
    log = {
        "negentropy": [0.6, 0.7, 0.4],
        "lz_complexity": [0.5, 0.45, 0.6],
        "symbiosis_score": [0.55, 0.6, 0.3],
        "clusters": [0, 0, 1],
    }
    fig, axes = plot_telemetry(log)
    assert len(axes) == 3
    fig.clf()


def test_metric_no_gradient_flow():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    bits = torch.randint(0, 2, (2, 8), dtype=torch.long)
    logits, _ = model(bits)
    loss = model.negentropy_logits(logits).mean() + model.lz_complexity_logits(logits).mean()
    assert not loss.requires_grad
    with pytest.raises(RuntimeError):
        loss.backward()


def test_negentropy_decompression_edge_case():
    bits = torch.tensor([0, 1] * 8, dtype=torch.uint8)
    comp = compress_bits(bits)
    model = BitTransformerLM(d_model=16, nhead=2, num_layers=1, dim_feedforward=32, max_seq_len=bits.numel())
    neg_comp = model.negentropy_kpi(comp.unsqueeze(0))
    neg_raw = model.negentropy_kpi(bits.unsqueeze(0))
    assert torch.allclose(neg_comp, neg_raw, atol=1e-6)


def test_dynamic_quantization():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    from bit_transformer import quantize_dynamic

    qmodel = quantize_dynamic(model)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, _ = qmodel(bits)
    assert logits.shape == (1, 8, 2)


def test_qat_fx_roundtrip():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    from bit_transformer import prepare_qat_fx, convert_qat_fx

    example_bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    qat_model = prepare_qat_fx(model)
    qat_model.eval()
    qmodel = convert_qat_fx(qat_model)

    logits, _ = qmodel(example_bits)
    assert logits.shape == (1, 8, 2)


def test_fsdp_wrap():
    import os
    import torch
    import torch.distributed as dist
    from bit_transformer import BitTransformerLM, wrap_fsdp

    if not dist.is_initialized():
        os.environ.setdefault("MASTER_ADDR", "localhost")
        os.environ.setdefault("MASTER_PORT", "29500")
        dist.init_process_group("gloo", rank=0, world_size=1)
    if not torch.cuda.is_available():
        pytest.skip("CUDA not available")
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    fsdp_model = wrap_fsdp(model)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, _ = fsdp_model(bits)
    assert logits.shape == (1, 8, 2)
    dist.destroy_process_group()


def test_make_pipeline():
    import pytest
    import torch.distributed.rpc as rpc
    from bit_transformer import BitTransformerLM, make_pipeline

    if not rpc._is_current_rpc_agent_set():
        pytest.skip("RPC not initialized")

    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    pipe_model = make_pipeline(model, chunks=1)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, _ = pipe_model(bits)
    assert logits.shape == (1, 8, 2)


def test_causal_attention():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    logits, tele = model(bits, causal=True)
    assert logits.shape == (1, 8, 2)
    attn = tele["attention_maps"][0]
    upper = attn.triu(1)
    assert torch.allclose(upper, torch.zeros_like(upper))


def test_scaling_helpers():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    model = model.double_width()
    assert model.d_model == 64
    model = model.double_layers()
    assert model.num_layers == 2


def test_expand_positional_encoding():
    model = BitTransformerLM(d_model=16, nhead=4, num_layers=1, dim_feedforward=32, max_seq_len=8)
    model.expand_positional_encoding(16)
    assert model.pos_enc.pe.size(0) == 16


def test_infer_long_sequence():
    model = BitTransformerLM(d_model=16, nhead=4, num_layers=1, dim_feedforward=32, max_seq_len=8)
    bits = torch.randint(0, 2, (12,), dtype=torch.long)
    preds, logs = infer_long_sequence(model, bits, ctx_bits=8, overlap=4)
    assert len(preds) == 12
    assert len(logs) >= 2


def test_chunking_disabled_when_non_causal():
    model = BitTransformerLM(
        d_model=32,
        nhead=4,
        num_layers=1,
        dim_feedforward=64,
        max_seq_len=8,
        chunk_size=2,
        full_attn_logging=True,
    )
    # Zero query/key/value projections so attention is uniformly distributed.
    # This makes the test deterministic: any non-masked position receives equal
    # weight, allowing us to rely solely on the chunking mask for the check.
    nn.init.constant_(model.layers[0].self_attn.in_proj_weight, 0.0)
    nn.init.constant_(model.layers[0].self_attn.in_proj_bias, 0.0)
    # Disable dropout for deterministic attention weights.
    model.eval()
    for module in model.modules():
        if isinstance(module, nn.Dropout):
            module.p = 0.0
    model.layers[0].self_attn.dropout = 0.0

    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    _, tele_causal = model(bits, causal=True)
    _, tele_noncausal = model(bits, causal=False)
    attn_causal = tele_causal["attention_maps"][0]
    attn_noncausal = tele_noncausal["attention_maps"][0]
    # Causal mode keeps attention within chunk boundaries, while non-causal mode
    # should permit cross-chunk attention.
    assert attn_causal[0, 0, 0, 4] == 0
    assert attn_noncausal[0, 0, 0, 4] > 0


def test_diffusion_inference_generates_bits():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    out = diffusion_inference(model, length=8, steps=2, batch_size=2)
    assert out.shape == (2, 8)
    assert set(out.unique().tolist()).issubset({0, 1})


def test_diffusion_inference_cosine_schedule():
    model = BitTransformerLM(d_model=32, nhead=4, num_layers=1, dim_feedforward=64, max_seq_len=8)
    out = diffusion_inference(model, length=8, steps=2, schedule="cosine")
    assert out.shape == (1, 8)


def test_chunking_restored_after_diffusion():
    model = BitTransformerLM(
        d_model=32,
        nhead=4,
        num_layers=1,
        dim_feedforward=64,
        max_seq_len=8,
        chunk_size=2,
        full_attn_logging=True,
    )
    bits = torch.randint(0, 2, (1, 8), dtype=torch.long)
    _ = model(bits, causal=False)
    assert model.layers[0].chunk_size == 2
    _, tele = model(bits, causal=True)
    attn = tele["attention_maps"][0]
    assert attn[0, 0, 0, 4] == 0