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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
"""Integration tests for draft model forward passes with real weights.

Covers DFlash, Eagle3, PEagle, and MTP models with shared parametrized tests
for training, multi-batch, and vocab boundary scenarios, plus model-specific
parameter variation tests.
"""

from collections.abc import Callable
from dataclasses import dataclass, field
from functools import partial
from typing import Any

import pytest
import torch

from speculators.models.mtp import shift_batch_mtp
from speculators.models.mtp.core import compute_step_weights
from tests.conftest import requires_cuda, requires_transformers_version
from tests.integration.conftest import (
    HIDDEN_SIZE,
    TINY_QWEN3_5_KWARGS,
    VOCAB_SIZE,
    make_batch,
    make_dflash_model,
    make_eagle3_model,
    make_mtp_model,
    make_peagle_model,
    make_sample,
)

MAX_LEN = 128
HIDDEN_MULTIPLIER = 3
LOSS_MASK_CASES = ["all", "none", "random", "alternating"]

SAMPLE_CONFIGS = [
    pytest.param([128], id="single_sample"),
    pytest.param([64, 64], id="two_equal"),
    pytest.param([32, 96], id="two_unequal"),
    pytest.param([8] * 20, id="twenty_tiny"),
]

MULTI_BATCH_CONFIGS: list[list[int]] = [
    [16, 16, 8, 10, 15, 12],
    [32, 32, 32],
    [64, 64],
    [32, 3, 17],
    [128],
    [16],
    [],
]

# ---------------------------------------------------------------------------
# Model specs
# ---------------------------------------------------------------------------

_requires_qwen3_5 = requires_transformers_version("5.2.0")


@dataclass(frozen=True)
class ModelSpec:
    name: str
    factory: Callable[..., Any]
    forward_kwargs: dict[str, Any] = field(default_factory=dict)
    hidden_size: int = HIDDEN_SIZE
    hidden_multiplier: int = HIDDEN_MULTIPLIER
    batch_factory: Callable[..., Any] = make_batch


DFLASH_SPEC = ModelSpec(
    name="dflash", factory=make_dflash_model, forward_kwargs={"max_anchors": 8}
)
EAGLE3_SPEC = ModelSpec(
    name="eagle3", factory=make_eagle3_model, forward_kwargs={"ttt_steps": 2}
)
PEAGLE_SPEC = ModelSpec(
    name="peagle",
    factory=make_peagle_model,
    forward_kwargs={
        "num_depths": 4,
        "down_sample_ratio": 0.7,
        "down_sample_ratio_min": 0.2,
    },
)
MTP_SPEC = ModelSpec(
    name="mtp",
    factory=make_mtp_model,
    forward_kwargs={"step_weights": [0.51, 0.31, 0.18]},
    hidden_size=TINY_QWEN3_5_KWARGS["hidden_size"],
    hidden_multiplier=1,
    batch_factory=partial(make_batch, num_target_layers=1, preprocess=shift_batch_mtp),
)

ALL_SPECS = [
    pytest.param(DFLASH_SPEC, id="dflash"),
    pytest.param(EAGLE3_SPEC, id="eagle3"),
    pytest.param(PEAGLE_SPEC, id="peagle"),
    pytest.param(MTP_SPEC, id="mtp", marks=_requires_qwen3_5),
]

VOCAB_SPECS = [
    pytest.param(DFLASH_SPEC, id="dflash"),
    pytest.param(EAGLE3_SPEC, id="eagle3"),
    pytest.param(PEAGLE_SPEC, id="peagle"),
]


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _make_samples(
    seq_lengths: list[int],
    loss_mask_pattern: str = "all",
    vocab_size: int = VOCAB_SIZE,
    hidden_size: int = HIDDEN_SIZE,
    hidden_multiplier: int = HIDDEN_MULTIPLIER,
    boundary_token_ids: list[int] | None = None,
) -> list[dict[str, torch.Tensor]]:
    return [
        make_sample(
            seq_len=sl,
            hidden_size=hidden_size,
            hidden_multiplier=hidden_multiplier,
            vocab_size=vocab_size,
            loss_mask_pattern=loss_mask_pattern,
            include_verifier_states=True,
            boundary_token_ids=boundary_token_ids,
        )
        for sl in seq_lengths
    ]


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture(params=ALL_SPECS)
def model_and_spec(request):
    spec: ModelSpec = request.param
    model = spec.factory()
    yield model, spec
    del model
    torch.cuda.empty_cache()


@pytest.fixture
def draft_vocab_model(request):
    spec: ModelSpec = request.param
    model = spec.factory(draft_vocab_size=32)
    t2d = torch.zeros(VOCAB_SIZE, dtype=torch.bool)
    t2d[:32] = True
    d2t = torch.arange(32, dtype=torch.long)
    model.load_vocab_mappings(t2d.to("cuda"), d2t.to("cuda"))
    yield model, spec
    del model
    torch.cuda.empty_cache()


# ---------------------------------------------------------------------------
# Shared tests
# ---------------------------------------------------------------------------


@requires_cuda
class TestTraining:
    """Forward + backward pass across all models."""

    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    @pytest.mark.parametrize("loss_mask_pattern", LOSS_MASK_CASES)
    def test_forward_backward(self, model_and_spec, seq_lengths, loss_mask_pattern):
        model, spec = model_and_spec
        samples = _make_samples(
            seq_lengths,
            loss_mask_pattern=loss_mask_pattern,
            hidden_size=spec.hidden_size,
            hidden_multiplier=spec.hidden_multiplier,
        )
        batch = spec.batch_factory(
            max_len=MAX_LEN, samples=samples, hidden_size=spec.hidden_size
        )
        draft_tokens, loss, metrics = model(**batch, **spec.forward_kwargs)

        assert loss.isfinite(), f"Loss is not finite: {loss.item()}"
        assert "loss_sum" in metrics
        assert "loss_total" in metrics
        loss.backward()


@requires_cuda
class TestMultiBatch:
    """Run multiple batches back-to-back to test statefulness and cache clearing."""

    def test_varying_batches(self, model_and_spec):
        model, spec = model_and_spec
        torch.compiler.reset()
        for seq_lengths in MULTI_BATCH_CONFIGS:
            samples = _make_samples(
                seq_lengths,
                hidden_size=spec.hidden_size,
                hidden_multiplier=spec.hidden_multiplier,
            )
            batch = spec.batch_factory(
                max_len=MAX_LEN, samples=samples, hidden_size=spec.hidden_size
            )
            draft_tokens, loss, metrics = model(**batch, **spec.forward_kwargs)
            assert loss.isfinite(), f"Loss not finite for seq_lengths={seq_lengths}"
            loss.backward()

    def test_varying_loss_masks_across_batches(self, model_and_spec):
        model, spec = model_and_spec
        torch.compiler.reset()
        for pattern in LOSS_MASK_CASES:
            samples = _make_samples(
                [64, 64],
                loss_mask_pattern=pattern,
                hidden_size=spec.hidden_size,
                hidden_multiplier=spec.hidden_multiplier,
            )
            batch = spec.batch_factory(
                max_len=MAX_LEN, samples=samples, hidden_size=spec.hidden_size
            )
            draft_tokens, loss, metrics = model(**batch, **spec.forward_kwargs)
            assert loss.isfinite(), f"Loss not finite for loss_mask_pattern={pattern}"
            loss.backward()


@requires_cuda
class TestVocabBoundary:
    """Tests with draft vocab mapping."""

    @pytest.mark.parametrize("draft_vocab_model", VOCAB_SPECS, indirect=True)
    def test_boundary_tokens(self, draft_vocab_model):
        model, spec = draft_vocab_model
        samples = _make_samples([128], vocab_size=32, boundary_token_ids=[0, 31])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, **spec.forward_kwargs)

        assert loss.isfinite()
        loss.backward()


# ---------------------------------------------------------------------------
# Model-specific parameter tests
# ---------------------------------------------------------------------------


@requires_cuda
class TestDFlashParams:
    @pytest.mark.parametrize("block_size", [2, 4, 8])
    def test_varying_block_size(self, block_size):
        model = make_dflash_model(block_size=block_size)
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, max_anchors=4)

        assert loss.isfinite()
        loss.backward()

    @pytest.mark.parametrize("max_anchors", [2, 8, 16])
    def test_varying_max_anchors(self, max_anchors):
        model = make_dflash_model()
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, max_anchors=max_anchors)

        assert loss.isfinite()
        loss.backward()

    @pytest.mark.parametrize("draft_attn_impl", ["sdpa", "eager"])
    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backend(self, draft_attn_impl, seq_lengths):
        model = make_dflash_model(draft_attn_impl=draft_attn_impl)
        samples = _make_samples(seq_lengths)
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, max_anchors=8)

        assert loss.isfinite()
        loss.backward()

    ATTN_BACKENDS = ["simple_flex_attention", "sdpa", "eager"]

    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backends_match(self, seq_lengths):
        """All attention backends produce equivalent outputs for the same input."""
        samples = _make_samples(seq_lengths)

        results = {}
        for backend in self.ATTN_BACKENDS:
            torch.manual_seed(0)
            model = make_dflash_model(draft_attn_impl=backend)
            batch = make_batch(
                max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE
            )
            _, loss, _ = model(**batch, max_anchors=8)
            results[backend] = loss.detach().cpu()
            del model
            torch.cuda.empty_cache()

        ref_backend = self.ATTN_BACKENDS[0]
        for backend in self.ATTN_BACKENDS[1:]:
            torch.testing.assert_close(
                results[backend],
                results[ref_backend],
                atol=1e-3,
                rtol=1e-3,
                msg=f"{backend} loss diverges from {ref_backend}",
            )


@requires_cuda
class TestEagle3Params:
    @pytest.mark.parametrize("ttt_steps", [1, 3, 5])
    def test_varying_ttt_steps(self, ttt_steps):
        model = make_eagle3_model()
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, ttt_steps=ttt_steps)

        assert len(draft_tokens) == ttt_steps
        for dt in draft_tokens:
            assert dt.shape == (1, MAX_LEN)
            assert dt.dtype == torch.long
        assert loss.isfinite()
        loss.backward()

    @pytest.mark.parametrize("draft_attn_impl", ["sdpa", "eager"])
    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backend(self, draft_attn_impl, seq_lengths):
        model = make_eagle3_model(draft_attn_impl=draft_attn_impl)
        samples = _make_samples(seq_lengths)
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, ttt_steps=2)

        assert loss.isfinite()
        loss.backward()

    ATTN_BACKENDS = ["simple_flex_attention", "sdpa", "eager"]

    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backends_match(self, seq_lengths):
        """All attention backends produce equivalent outputs for the same input."""
        samples = _make_samples(seq_lengths)

        results = {}
        for backend in self.ATTN_BACKENDS:
            torch.manual_seed(0)
            model = make_eagle3_model(draft_attn_impl=backend)
            batch = make_batch(
                max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE
            )
            _, loss, _ = model(**batch, ttt_steps=2)
            results[backend] = loss.detach().cpu()
            del model
            torch.cuda.empty_cache()

        ref_backend = self.ATTN_BACKENDS[0]
        for backend in self.ATTN_BACKENDS[1:]:
            torch.testing.assert_close(
                results[backend],
                results[ref_backend],
                atol=1e-3,
                rtol=1e-3,
                msg=f"{backend} loss diverges from {ref_backend}",
            )


@requires_cuda
class TestNormOutputParams:
    """Tests for Eagle 3.1: norm_before_fc + norm_output."""

    def test_norm_output(self):
        model = make_eagle3_model(norm_before_fc=True, norm_output=True)
        assert model.input_norm is not None
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, _metrics = model(**batch, ttt_steps=3)

        assert len(draft_tokens) == 3
        assert loss.isfinite()
        loss.backward()

    def test_norm_output_without_norm_before_fc(self):
        model = make_eagle3_model(norm_output=True)
        assert model.input_norm is None
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, _metrics = model(**batch, ttt_steps=3)

        assert len(draft_tokens) == 3
        assert loss.isfinite()
        loss.backward()

    def test_fc_norm(self):
        model = make_eagle3_model(fc_norm=True, norm_output=True)
        assert model.fc_norm is not None
        assert len(model.fc_norm) == 3
        assert model.input_norm is None
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, _metrics = model(**batch, ttt_steps=3)

        assert len(draft_tokens) == 3
        assert loss.isfinite()
        loss.backward()

    def test_peagle_fc_norm(self):
        model = make_peagle_model(fc_norm=True)
        assert model.fc_norm is not None
        assert len(model.fc_norm) == 3
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        _draft_tokens, loss, _metrics = model(**batch, num_depths=4)

        assert loss.isfinite()
        loss.backward()

    def test_peagle_norm_before_fc(self):
        model = make_peagle_model()
        assert model.input_norm is None

        model = make_peagle_model(norm_before_fc=True)
        assert model.input_norm is not None
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        _draft_tokens, loss, _metrics = model(**batch, num_depths=4)

        assert loss.isfinite()
        loss.backward()


@requires_cuda
class TestPEagleParams:
    @pytest.mark.parametrize("num_depths", [2, 4, 8])
    def test_varying_num_depths(self, num_depths):
        model = make_peagle_model(num_depths=num_depths)
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, num_depths=num_depths)

        assert loss.isfinite()
        loss.backward()

    @pytest.mark.parametrize("down_sample_ratio", [0.3, 0.7, 1.0])
    def test_varying_down_sample_ratio(self, down_sample_ratio):
        model = make_peagle_model()
        samples = _make_samples([128])
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(
            **batch, num_depths=4, down_sample_ratio=down_sample_ratio
        )

        assert loss.isfinite()
        loss.backward()

    @pytest.mark.parametrize("draft_attn_impl", ["sdpa", "eager"])
    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backend(self, draft_attn_impl, seq_lengths):
        model = make_peagle_model(draft_attn_impl=draft_attn_impl)
        samples = _make_samples(seq_lengths)
        batch = make_batch(max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE)
        draft_tokens, loss, metrics = model(**batch, num_depths=4)

        assert loss.isfinite()
        loss.backward()

    ATTN_BACKENDS = ["simple_flex_attention", "sdpa", "eager"]

    @pytest.mark.parametrize("seq_lengths", SAMPLE_CONFIGS)
    def test_attention_backends_match(self, seq_lengths):
        """All attention backends produce equivalent outputs for the same input."""
        samples = _make_samples(seq_lengths)

        results = {}
        for backend in self.ATTN_BACKENDS:
            torch.manual_seed(0)
            model = make_peagle_model(draft_attn_impl=backend)
            batch = make_batch(
                max_len=MAX_LEN, samples=samples, hidden_size=HIDDEN_SIZE
            )
            _, loss, _ = model(**batch, num_depths=4)
            results[backend] = loss.detach().cpu()
            del model
            torch.cuda.empty_cache()

        ref_backend = self.ATTN_BACKENDS[0]
        for backend in self.ATTN_BACKENDS[1:]:
            torch.testing.assert_close(
                results[backend],
                results[ref_backend],
                atol=1e-3,
                rtol=1e-3,
                msg=f"{backend} loss diverges from {ref_backend}",
            )


@requires_cuda
@requires_transformers_version("5.2.0")
class TestMTPParams:
    @pytest.mark.parametrize("num_speculative_steps", [1, 2, 5])
    def test_varying_num_speculative_steps(self, num_speculative_steps):
        model = make_mtp_model(
            num_speculative_steps=num_speculative_steps, torch_compile=False
        )
        step_weights = compute_step_weights(num_steps=num_speculative_steps)
        samples = _make_samples(
            [128],
            hidden_size=TINY_QWEN3_5_KWARGS["hidden_size"],
            hidden_multiplier=1,
            vocab_size=TINY_QWEN3_5_KWARGS["vocab_size"],
        )
        batch = make_batch(
            max_len=MAX_LEN,
            samples=samples,
            hidden_size=TINY_QWEN3_5_KWARGS["hidden_size"],
            num_target_layers=1,
            preprocess=shift_batch_mtp,
        )
        logits_list, loss, metrics = model(**batch, step_weights=step_weights)

        assert loss.isfinite()
        loss.backward()