"""Unit tests for PR #40 performance optimizations and review invariants. Covers: 1. CPUOffloadPool coalesced slab batching, group_hint separation, offload_early (full and partial slabs), peak temporary GPU memory <= 32 MB, post-init track() guard, and non-contiguous tensor rejection. 2. fused_wd_add_ Triton kernels (contiguous fp32/bf16/fp16, transposed 3D w2 fp32/bf16, empty tensors, CPU / mismatch fallbacks). 3. pipeline._is_contiguous_dim0_shards & _complete_gather fast path (1-rank, multi-rank, empty shape, rank_numels mismatch fallback, and in-place buffer reuse without double allocation). 4. Muon routing cache invalidation on load_state_dict(), p.data replacement, in-place param-list mutation, and _setup_parallel param_ids refresh. """ import pytest import torch from optimizer.core import _muon_state from optimizer.cpu_offload import _SLAB_MAX_BYTES, CPUOffloadPool from optimizer.muon import Muon from optimizer.newton_schulz import COMM_DTYPE, fused_wd_add_, set_ns_compile from optimizer.pipeline import _complete_gather, _is_contiguous_dim0_shards # --------------------------------------------------------------------------- # 1. CPUOffloadPool slab batching & peak GPU memory bound # --------------------------------------------------------------------------- @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") def test_cpu_offload_slab_batching_and_peak_memory(): device = torch.device("cuda", 0) pool = CPUOffloadPool() # Create enough small tensors (> 3 slabs = ~96 MB) across two group_hints # plus one large direct tensor and one tagged tensor. torch.manual_seed(0) adam_tensors = [ torch.randn(512 * 1024, dtype=torch.float32, device=device) # 2 MB each for _ in range(36) # 72 MB -> 3 slabs ] muon_tensors = [ torch.randn(512 * 1024, dtype=torch.bfloat16, device=device) # 1 MB each for _ in range(40) # 40 MB -> 2 slabs ] large_tensor = torch.randn(2 * 1024 * 1024, dtype=torch.float32, device=device) # 8 MB (> 4 MB -> direct) tagged_tensor = torch.randn(256 * 1024, dtype=torch.float32, device=device) # 1 MB (tagged -> direct) originals = ( [t.clone() for t in adam_tensors] + [t.clone() for t in muon_tensors] + [large_tensor.clone(), tagged_tensor.clone()]) for t in adam_tensors: pool.track(t, group_hint="adamw") for t in muon_tensors: pool.track(t, group_hint="muon") pool.track(large_tensor, group_hint="adamw") pool.track(tagged_tensor, tag="layer_0") # Non-contiguous tensor must be rejected. non_contig = torch.randn(64, 64, device=device).t() with pytest.raises(ValueError, match="contiguous"): pool.track(non_contig) # First offload initializes buffers and slabs. pool.offload() assert len(pool._untagged_slabs) >= 4 assert all(t.untyped_storage().size() == 0 for t in adam_tensors + muon_tensors + [large_tensor, tagged_tensor]) # Post-init track() must fail fast instead of causing IndexError later. extra = torch.randn(16, device=device) with pytest.raises(RuntimeError, match="after CPUOffloadPool has been initialized"): pool.track(extra) # Measure peak temporary GPU memory during reload_untagged() across >= 4 slabs. torch.cuda.synchronize(device) torch.cuda.empty_cache() base_alloc = torch.cuda.memory_allocated(device) torch.cuda.reset_peak_memory_stats(device) pool.reload_untagged() pool.wait_reload() pool.reload_group("layer_0") pool.wait_reload() torch.cuda.synchronize(device) expected_restored = sum(t.numel() * t.element_size() for t in adam_tensors + muon_tensors + [large_tensor, tagged_tensor]) peak_extra = torch.cuda.max_memory_allocated( device) - base_alloc - expected_restored # Single reused staging buffer must stay within 1 slab (+ small allocator rounding). assert peak_extra <= _SLAB_MAX_BYTES + 2 * 1024 * 1024, ( f"Expected temporary GPU staging <= 32 MB, got {peak_extra / (1024**2):.2f} MB" ) # Verify bit-exact roundtrip. all_tensors = adam_tensors + muon_tensors + [large_tensor, tagged_tensor] for cur, orig in zip(all_tensors, originals): assert torch.equal(cur, orig) # Mutate tensors, then test offload_early with: # - a full muon hint slab (all muon_tensors) # - a partial adamw slab (first 3 adam_tensors) # followed by full offload() + reload(). for t in all_tensors: t.add_(1.5) updated = [t.clone() for t in all_tensors] pool.offload_early(muon_tensors) pool.offload_early(adam_tensors[:3]) pool.offload() pool.reload() pool.wait_reload() torch.cuda.synchronize(device) for cur, exp in zip(all_tensors, updated): assert torch.equal(cur, exp) # --------------------------------------------------------------------------- # 2. fused_wd_add_ (contiguous, transposed 3D, bf16/fp16/fp32, empty, fallback) # --------------------------------------------------------------------------- @pytest.mark.parametrize("w_dtype", [torch.float32, torch.bfloat16, torch.float16]) @pytest.mark.parametrize("u_dtype", [torch.bfloat16, torch.float32]) @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") def test_fused_wd_add_contiguous_cuda(w_dtype, u_dtype): torch.manual_seed(42) w = torch.randn(3, 129, 257, dtype=w_dtype, device="cuda") u = torch.randn(3, 129, 257, dtype=u_dtype, device="cuda") wd_scale, neg_lr = 0.999, -0.02 ref = (w.float() * wd_scale + neg_lr * u.float()).to(w_dtype) fused_wd_add_(w, u, wd_scale, neg_lr) tol = 1e-5 if w_dtype == torch.float32 else 1e-2 torch.testing.assert_close(w, ref, rtol=tol, atol=tol) @pytest.mark.parametrize("w_dtype", [torch.float32, torch.bfloat16]) @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") def test_fused_wd_add_transposed_3d_cuda(w_dtype): torch.manual_seed(7) B, M, N = 4, 130, 195 w = torch.randn(B, M, N, dtype=w_dtype, device="cuda") # u has shape (B, M, N) with stride(1) == 1 (transposed from contiguous (B, N, M)) u_src = torch.randn(B, N, M, dtype=torch.bfloat16, device="cuda") u = u_src.transpose(-1, -2) assert u.shape == w.shape and u.stride(1) == 1 and not u.is_contiguous() wd_scale, neg_lr = 0.998, -0.015 ref = (w.float() * wd_scale + neg_lr * u.float()).to(w_dtype) fused_wd_add_(w, u, wd_scale, neg_lr) tol = 1e-5 if w_dtype == torch.float32 else 1e-2 torch.testing.assert_close(w, ref, rtol=tol, atol=tol) def test_fused_wd_add_empty_and_cpu_fallback(): # Empty tensors should return cleanly without launching a 0-grid kernel. w_empty = torch.empty(0, 64, dtype=torch.float32) u_empty = torch.empty(0, 64, dtype=torch.bfloat16) fused_wd_add_(w_empty, u_empty, 0.99, -0.01) if torch.cuda.is_available(): w_ec = torch.empty(0, 64, dtype=torch.float32, device="cuda") u_ec = torch.empty(0, 64, dtype=torch.bfloat16, device="cuda") fused_wd_add_(w_ec, u_ec, 0.99, -0.01) # CPU fallback matches mul_ + add_. w_cpu = torch.randn(8, 16, dtype=torch.float32) u_cpu = torch.randn(8, 16, dtype=torch.float32) ref = w_cpu * 0.95 - 0.05 * u_cpu fused_wd_add_(w_cpu, u_cpu, 0.95, -0.05) torch.testing.assert_close(w_cpu, ref) # Shape mismatch must still raise instead of silently returning or crashing. w_bad = torch.randn(4, 8) u_bad = torch.randn(4, 16) with pytest.raises(RuntimeError): fused_wd_add_(w_bad, u_bad, 0.99, -0.01) # --------------------------------------------------------------------------- # 3. _is_contiguous_dim0_shards & _complete_gather in-place buffer reuse # --------------------------------------------------------------------------- def _make_state(rank_indices, rank_numels, worker_rank=0): return _muon_state( worker_rank=worker_rank, process_group=None, rank_indices=rank_indices, rank_numels=rank_numels, name="layer.weight", ) def test_is_contiguous_dim0_shards_edge_cases(): # Empty shapes must return False (avoiding torch.cat([]) crash). st_empty0 = _make_state([(slice(0, 0), slice(None))], [0]) assert not _is_contiguous_dim0_shards(st_empty0, (0, 8), 1) st_empty1 = _make_state([(slice(0, 4), slice(None))], [0]) assert not _is_contiguous_dim0_shards(st_empty1, (4, 0), 1) # Valid 2-rank dim-0 partition. st_ok = _make_state( [(slice(0, 4), slice(None)), (slice(4, 8), slice(None))], [4 * 6, 4 * 6], ) assert _is_contiguous_dim0_shards(st_ok, (8, 6), 2) # Mismatched rank_numels must return False. st_bad_numel = _make_state( [(slice(0, 4), slice(None)), (slice(4, 8), slice(None))], [4 * 6 - 1, 4 * 6 + 1], ) assert not _is_contiguous_dim0_shards(st_bad_numel, (8, 6), 2) # Non-dim-0 shard (column sharding) must return False. st_col = _make_state( [(slice(None), slice(0, 3)), (slice(None), slice(3, 6))], [8 * 3, 8 * 3], ) assert not _is_contiguous_dim0_shards(st_col, (8, 6), 2) @pytest.mark.parametrize("num_ranks", [1, 3]) def test_complete_gather_fast_path_reuses_buffer_inplace(num_ranks): rows_per_rank, cols = 4, 6 full = torch.arange(num_ranks * rows_per_rank * cols, dtype=COMM_DTYPE).reshape(num_ranks * rows_per_rank, cols) p = torch.empty_like(full) rank_indices = [(slice(r * rows_per_rank, (r + 1) * rows_per_rank), slice(None)) for r in range(num_ranks)] rank_numels = [rows_per_rank * cols] * num_ranks state = _make_state(rank_indices, rank_numels) prealloc = torch.empty(p.shape, dtype=COMM_DTYPE) prealloc_ptr = prealloc.data_ptr() gathered_grads = {id(p): prealloc} recv_buf = full.reshape(-1).clone() _complete_gather( recv_buf=recv_buf, recv_counts=rank_numels, owned_params=[p], gathered_grads=gathered_grads, param_to_state={id(p): state}, rank=0, ) assert state._fast_dim0_gather is True # Must write in-place into the pre-allocated buffer (no double allocation). assert gathered_grads[id(p)] is prealloc assert gathered_grads[id(p)].data_ptr() == prealloc_ptr assert torch.equal(gathered_grads[id(p)], full) def test_complete_gather_fallback_on_col_sharding(): full = torch.arange(8 * 6, dtype=COMM_DTYPE).reshape(8, 6) p = torch.empty_like(full) state = _make_state( [(slice(None), slice(0, 3)), (slice(None), slice(3, 6))], [8 * 3, 8 * 3], ) prealloc = torch.empty(p.shape, dtype=COMM_DTYPE) gathered_grads = {id(p): prealloc} recv_buf = torch.cat([full[:, :3].reshape(-1), full[:, 3:].reshape(-1)]) _complete_gather( recv_buf=recv_buf, recv_counts=[8 * 3, 8 * 3], owned_params=[p], gathered_grads=gathered_grads, param_to_state={id(p): state}, rank=0, ) assert state._fast_dim0_gather is False assert torch.equal(gathered_grads[id(p)], full) # --------------------------------------------------------------------------- # 4. Muon routing cache invalidation (load_state_dict / p.data / list mutation) # --------------------------------------------------------------------------- @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") def test_muon_route_cache_invalidation_and_pdata_swap(): set_ns_compile(False) torch.manual_seed(123) device = torch.device("cuda", 0) w_exp = torch.nn.Parameter( torch.randn(2, 16, 16, dtype=torch.float32, device=device)) w_dense = torch.nn.Parameter( torch.randn(16, 16, dtype=torch.float32, device=device)) opt = Muon( [{ "params": [w_exp, w_dense], "names": ["layers.0.moe.experts.w1", "layers.0.attn.wq"], "use_muon": True, "lr": 0.05, "momentum": 0.95, "weight_decay": 0.01, "nesterov": True, "ns_steps": 5, }], expert_keys=["experts.w1"], ) # Step 1 populates _step_route_cache and _dt_group_cache. w_exp.grad = torch.randn_like(w_exp) w_dense.grad = torch.randn_like(w_dense) opt.step() assert len(getattr(opt, "_step_route_cache", {})) == 1 assert len(getattr(opt, "_dt_group_cache", {})) == 1 # Replacing w_exp.data MUST still update the new tensor (never the stale orphan). old_data = w_exp.data old_snap = old_data.clone() new_data = torch.randn_like(w_exp) new_snap = new_data.clone() w_exp.data = new_data w_exp.grad = torch.randn_like(w_exp) w_dense.grad = torch.randn_like(w_dense) opt.step() assert torch.equal(old_data, old_snap), "Stale orphaned tensor was silently mutated!" assert not torch.equal(w_exp.data, new_snap), "New w_exp.data was not updated!" # Mutating group["params"] in-place with a new Parameter object must not collide. w_exp2 = torch.nn.Parameter( torch.randn(2, 16, 16, dtype=torch.float32, device=device)) w_exp2_snap = w_exp2.data.clone() opt.state.pop(w_exp, None) opt.param_groups[0]["params"][0] = w_exp2 w_exp2.grad = torch.randn_like(w_exp2) w_dense.grad = torch.randn_like(w_dense) opt.step() assert not torch.equal(w_exp2.data, w_exp2_snap), "Replaced param was not updated!" # load_state_dict() must clear all routing caches. sd = opt.state_dict() opt.load_state_dict(sd) assert len(opt._parallel_cache) == 0 assert len(opt._expert_expand_cache) == 0 assert len(opt._step_route_cache) == 0 assert len(opt._dt_group_cache) == 0