|
| 1 | +"""Tests for separated forward_streaming / backward_streaming API. |
| 2 | +
|
| 3 | +Verifies gradient correctness against a non-streaming reference model, |
| 4 | +and tests gradient accumulation and training convergence. |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import tempfile |
| 9 | + |
| 10 | +import pytest |
| 11 | +import torch |
| 12 | + |
| 13 | +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") |
| 14 | + |
| 15 | + |
| 16 | +def _make_model_pair(): |
| 17 | + """Create matching non-streaming and streaming models from same checkpoint.""" |
| 18 | + from transformers import LlamaConfig, LlamaForCausalLM |
| 19 | + |
| 20 | + from bitsandbytes.checkpoint import save_quantized, save_lora |
| 21 | + from bitsandbytes.kbit_lora import KbitLoraModel |
| 22 | + |
| 23 | + config = LlamaConfig( |
| 24 | + hidden_size=256, |
| 25 | + num_hidden_layers=2, |
| 26 | + num_attention_heads=4, |
| 27 | + num_key_value_heads=2, |
| 28 | + intermediate_size=512, |
| 29 | + vocab_size=1000, |
| 30 | + max_position_embeddings=256, |
| 31 | + ) |
| 32 | + model = LlamaForCausalLM(config).to(torch.float16).cuda() |
| 33 | + |
| 34 | + kbit = KbitLoraModel( |
| 35 | + model, lora_r=4, lora_alpha=8.0, k=4, |
| 36 | + attn_chunk_size=64, mlp_chunk_size=64, ce_chunk_size=256, |
| 37 | + compute_dtype=torch.bfloat16, |
| 38 | + ) |
| 39 | + |
| 40 | + tmpdir = tempfile.mkdtemp() |
| 41 | + quant_path = os.path.join(tmpdir, "quant.safetensors") |
| 42 | + lora_path = os.path.join(tmpdir, "lora.safetensors") |
| 43 | + save_quantized(kbit, quant_path) |
| 44 | + save_lora(kbit, lora_path) |
| 45 | + |
| 46 | + # Non-streaming reference (standard autograd works correctly) |
| 47 | + non_streaming = KbitLoraModel.from_quantized( |
| 48 | + quant_path, lora_r=4, lora_alpha=8.0, |
| 49 | + attn_chunk_size=64, mlp_chunk_size=64, ce_chunk_size=256, |
| 50 | + compute_dtype=torch.bfloat16, |
| 51 | + weight_streaming=False, |
| 52 | + lora_checkpoint=lora_path, |
| 53 | + ) |
| 54 | + |
| 55 | + # Streaming model |
| 56 | + streaming = KbitLoraModel.from_quantized( |
| 57 | + quant_path, lora_r=4, lora_alpha=8.0, |
| 58 | + attn_chunk_size=64, mlp_chunk_size=64, ce_chunk_size=256, |
| 59 | + compute_dtype=torch.bfloat16, |
| 60 | + weight_streaming=True, |
| 61 | + lora_checkpoint=lora_path, |
| 62 | + ) |
| 63 | + |
| 64 | + return non_streaming, streaming, tmpdir |
| 65 | + |
| 66 | + |
| 67 | +@pytest.fixture(scope="module") |
| 68 | +def model_pair(): |
| 69 | + non_streaming, streaming, tmpdir = _make_model_pair() |
| 70 | + yield non_streaming, streaming |
| 71 | + import shutil |
| 72 | + shutil.rmtree(tmpdir, ignore_errors=True) |
| 73 | + |
| 74 | + |
| 75 | +class TestForwardBackwardSeparation: |
| 76 | + |
| 77 | + def test_gradient_match(self, model_pair): |
| 78 | + """Streaming gradients must match non-streaming standard forward+backward.""" |
| 79 | + non_streaming, streaming = model_pair |
| 80 | + input_ids = torch.randint(0, 100, (1, 32), device="cuda") |
| 81 | + labels = input_ids.clone() |
| 82 | + |
| 83 | + # ─── Reference: non-streaming forward() + loss.backward() ─── |
| 84 | + non_streaming.train() |
| 85 | + for p in non_streaming.get_trainable_parameters(): |
| 86 | + p.grad = None |
| 87 | + |
| 88 | + result = non_streaming(input_ids, labels=labels) |
| 89 | + result["loss"].backward() |
| 90 | + |
| 91 | + grads_ref = {} |
| 92 | + for name, p in non_streaming._lora_params.items(): |
| 93 | + if p.grad is not None: |
| 94 | + grads_ref[name] = p.grad.clone() |
| 95 | + for name, p in non_streaming._norm_weights.items(): |
| 96 | + if p.grad is not None: |
| 97 | + grads_ref[f"norm_{name}"] = p.grad.clone() |
| 98 | + |
| 99 | + loss_ref = result["loss"].detach() |
| 100 | + |
| 101 | + # ─── Streaming: forward_streaming + backward_streaming ─── |
| 102 | + for p in streaming.get_trainable_parameters(): |
| 103 | + p.grad = None |
| 104 | + |
| 105 | + loss_stream, ctx = streaming.forward_streaming(input_ids, labels) |
| 106 | + streaming.backward_streaming(ctx) |
| 107 | + |
| 108 | + grads_stream = {} |
| 109 | + for name, p in streaming._lora_params.items(): |
| 110 | + if p.grad is not None: |
| 111 | + grads_stream[name] = p.grad.clone() |
| 112 | + for name, p in streaming._norm_weights.items(): |
| 113 | + if p.grad is not None: |
| 114 | + grads_stream[f"norm_{name}"] = p.grad.clone() |
| 115 | + |
| 116 | + # Compare losses |
| 117 | + assert torch.allclose(loss_ref, loss_stream, atol=1e-5), \ |
| 118 | + f"Loss mismatch: {loss_ref.item()} vs {loss_stream.item()}" |
| 119 | + |
| 120 | + # Compare gradients |
| 121 | + assert set(grads_ref.keys()) == set(grads_stream.keys()), \ |
| 122 | + f"Gradient key mismatch: {set(grads_ref) - set(grads_stream)} vs {set(grads_stream) - set(grads_ref)}" |
| 123 | + |
| 124 | + for name in grads_ref: |
| 125 | + assert torch.allclose(grads_ref[name], grads_stream[name], atol=1e-5, rtol=1e-4), \ |
| 126 | + f"Gradient mismatch for {name}: max diff {(grads_ref[name] - grads_stream[name]).abs().max().item()}" |
| 127 | + |
| 128 | + def test_loss_curve_match(self, model_pair): |
| 129 | + """Loss curves must match between non-streaming and streaming over 20 steps.""" |
| 130 | + non_streaming, streaming = model_pair |
| 131 | + lr = 1e-3 |
| 132 | + |
| 133 | + # Set both models to same initial state |
| 134 | + for (n1, p1), (n2, p2) in zip( |
| 135 | + non_streaming._lora_params.items(), streaming._lora_params.items() |
| 136 | + ): |
| 137 | + torch.manual_seed(42) |
| 138 | + val = torch.randn_like(p1.data) * 0.01 |
| 139 | + p1.data.copy_(val) |
| 140 | + p2.data.copy_(val) |
| 141 | + for (n1, p1), (n2, p2) in zip( |
| 142 | + non_streaming._norm_weights.items(), streaming._norm_weights.items() |
| 143 | + ): |
| 144 | + p1.data.fill_(1.0) |
| 145 | + p2.data.fill_(1.0) |
| 146 | + |
| 147 | + losses_ref = [] |
| 148 | + losses_stream = [] |
| 149 | + |
| 150 | + for step in range(20): |
| 151 | + torch.manual_seed(step + 1000) |
| 152 | + input_ids = torch.randint(0, 100, (1, 32), device="cuda") |
| 153 | + labels = input_ids.clone() |
| 154 | + |
| 155 | + # Non-streaming |
| 156 | + non_streaming.train() |
| 157 | + for p in non_streaming.get_trainable_parameters(): |
| 158 | + p.grad = None |
| 159 | + result = non_streaming(input_ids, labels=labels) |
| 160 | + result["loss"].backward() |
| 161 | + losses_ref.append(result["loss"].item()) |
| 162 | + for p in non_streaming.get_trainable_parameters(): |
| 163 | + if p.grad is not None: |
| 164 | + p.data.add_(p.grad, alpha=-lr) |
| 165 | + |
| 166 | + # Streaming |
| 167 | + for p in streaming.get_trainable_parameters(): |
| 168 | + p.grad = None |
| 169 | + loss_s, ctx = streaming.forward_streaming(input_ids, labels) |
| 170 | + streaming.backward_streaming(ctx) |
| 171 | + losses_stream.append(loss_s.item()) |
| 172 | + for p in streaming.get_trainable_parameters(): |
| 173 | + if p.grad is not None: |
| 174 | + p.data.add_(p.grad, alpha=-lr) |
| 175 | + |
| 176 | + # Losses should match at each step |
| 177 | + for i, (lr_val, ls_val) in enumerate(zip(losses_ref, losses_stream)): |
| 178 | + if lr_val == 0: |
| 179 | + continue |
| 180 | + rel_diff = abs(lr_val - ls_val) / abs(lr_val) |
| 181 | + assert rel_diff < 0.05, \ |
| 182 | + f"Step {i}: ref loss {lr_val:.6f} vs stream loss {ls_val:.6f} (rel diff {rel_diff:.4f})" |
| 183 | + |
| 184 | + def test_context_freed_after_backward(self, model_pair): |
| 185 | + """backward_streaming should free the context's checkpoint memory.""" |
| 186 | + _, streaming = model_pair |
| 187 | + input_ids = torch.randint(0, 100, (1, 32), device="cuda") |
| 188 | + labels = input_ids.clone() |
| 189 | + |
| 190 | + for p in streaming.get_trainable_parameters(): |
| 191 | + p.grad = None |
| 192 | + |
| 193 | + _, ctx = streaming.forward_streaming(input_ids, labels) |
| 194 | + assert len(ctx.checkpoints) > 0 |
| 195 | + |
| 196 | + streaming.backward_streaming(ctx) |
| 197 | + assert len(ctx.checkpoints) == 0 |
| 198 | + assert ctx.hidden_final is None |
| 199 | + assert ctx.grad_from_loss is None |
| 200 | + |
| 201 | + def test_gradient_accumulation(self, model_pair): |
| 202 | + """Multiple forward_streaming + backward_streaming calls should accumulate gradients.""" |
| 203 | + _, streaming = model_pair |
| 204 | + |
| 205 | + for p in streaming.get_trainable_parameters(): |
| 206 | + p.grad = None |
| 207 | + |
| 208 | + # Two micro-batches |
| 209 | + for _ in range(2): |
| 210 | + input_ids = torch.randint(0, 100, (1, 32), device="cuda") |
| 211 | + labels = input_ids.clone() |
| 212 | + |
| 213 | + _, ctx = streaming.forward_streaming(input_ids, labels) |
| 214 | + streaming.backward_streaming(ctx) |
| 215 | + |
| 216 | + # At least some parameters should have gradients |
| 217 | + has_grad = False |
| 218 | + for p in streaming.get_trainable_parameters(): |
| 219 | + if p.grad is not None and p.grad.abs().sum() > 0: |
| 220 | + has_grad = True |
| 221 | + break |
| 222 | + assert has_grad, "No gradients after 2 micro-batches" |
0 commit comments