Module neuralops.tests.test_low_accuracy_modules_fixes
Unit tests validating fixes for low-accuracy modules: - GPT-2 fused c_attn splitting prior to SVD - Aegis family positive gate bias and residual connection - Kronecker / FMS normalized positive denominator - Compressed attention pretrained weight copy & Frobenius norm >= 1e-4 - Cluster attention padding token filtering
Classes
class FakeGPT2Attention (embed_dim: int = 64)-
Expand source code
class FakeGPT2Attention(nn.Module): def __init__(self, embed_dim: int = 64): super().__init__() self.c_attn = nn.Linear(embed_dim, 3 * embed_dim) self.c_proj = nn.Linear(embed_dim, embed_dim) self.split_size = embed_dimBase class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes::
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:
to, etc.Note
As per the example above, an
__init__()call to the parent class must be made before assignment on the child.:ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Ancestors
- torch.nn.modules.module.Module
class TestLowAccuracyModulesFixes (methodName='runTest')-
Expand source code
class TestLowAccuracyModulesFixes(unittest.TestCase): def test_gpt2_c_attn_split_before_svd(self): """GPT-2 c_attn is split into Q, K, V before SVD rather than factorizing fused matrix.""" orig = FakeGPT2Attention(embed_dim=64) asvd = ASVDAttention(hidden_size=64, num_heads=4, is_decoder=True) asvd.copy_weights(orig) # Ensure query, key, value weights each have Frobenius norm >= 1e-4 for proj in (asvd.query, asvd.key, asvd.value, asvd.out_proj): w = proj.weight if hasattr(proj, "weight") else proj.get_weight() norm = torch.linalg.norm(w.float()).item() self.assertGreater(norm, 1e-4) def test_fms_positive_denominators(self): """FMS uses positive ELU+1 kernel feature maps preventing negative denominator explosions.""" fms = FactorisedMatrixState(d_model=64, num_heads=4, is_decoder=True) x = torch.randn(2, 32, 64) out, _ = fms(x) self.assertTrue(torch.isfinite(out).all()) self.assertFalse(torch.isnan(out).any()) def test_cluster_padding_exclusion(self): """Cluster attention excludes padding tokens from centroid calculation.""" cluster_attn = ClusterAttention(hidden_size=64, num_heads=4, num_clusters=4) x = torch.randn(2, 16, 64) # Sequence 2 has last 8 tokens as padding mask = torch.ones(2, 16) mask[1, 8:] = 0.0 out, _ = cluster_attn(x, attention_mask=mask) self.assertTrue(torch.isfinite(out).all()) def test_compressed_attention_weight_copy(self): """CompressedAttention copies pretrained weights and validates Frobenius norm >= 1e-4.""" orig = nn.MultiheadAttention(embed_dim=64, num_heads=4, batch_first=True) comp = CompressedAttention(hidden_size=64, num_heads=4, rank=16) comp.copy_weights(orig) for proj in (comp.query, comp.key, comp.value): w = proj.weight if hasattr(proj, "weight") else proj.get_weight() norm = torch.linalg.norm(w.float()).item() self.assertGreater(norm, 1e-4)A class whose instances are single test cases.
By default, the test code itself should be placed in a method named 'runTest'.
If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute.
Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively.
If it is necessary to override the init method, the base class init method must always be called. It is important that subclasses should not change the signature of their init method, since instances of the classes are instantiated automatically by parts of the framework in order to be run.
When subclassing TestCase, you can set these attributes: * failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'. * longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in addition to any explicit message passed. * maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required.
Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.
Ancestors
- unittest.case.TestCase
Methods
def test_cluster_padding_exclusion(self)-
Expand source code
def test_cluster_padding_exclusion(self): """Cluster attention excludes padding tokens from centroid calculation.""" cluster_attn = ClusterAttention(hidden_size=64, num_heads=4, num_clusters=4) x = torch.randn(2, 16, 64) # Sequence 2 has last 8 tokens as padding mask = torch.ones(2, 16) mask[1, 8:] = 0.0 out, _ = cluster_attn(x, attention_mask=mask) self.assertTrue(torch.isfinite(out).all())Cluster attention excludes padding tokens from centroid calculation.
def test_compressed_attention_weight_copy(self)-
Expand source code
def test_compressed_attention_weight_copy(self): """CompressedAttention copies pretrained weights and validates Frobenius norm >= 1e-4.""" orig = nn.MultiheadAttention(embed_dim=64, num_heads=4, batch_first=True) comp = CompressedAttention(hidden_size=64, num_heads=4, rank=16) comp.copy_weights(orig) for proj in (comp.query, comp.key, comp.value): w = proj.weight if hasattr(proj, "weight") else proj.get_weight() norm = torch.linalg.norm(w.float()).item() self.assertGreater(norm, 1e-4)CompressedAttention copies pretrained weights and validates Frobenius norm >= 1e-4.
def test_fms_positive_denominators(self)-
Expand source code
def test_fms_positive_denominators(self): """FMS uses positive ELU+1 kernel feature maps preventing negative denominator explosions.""" fms = FactorisedMatrixState(d_model=64, num_heads=4, is_decoder=True) x = torch.randn(2, 32, 64) out, _ = fms(x) self.assertTrue(torch.isfinite(out).all()) self.assertFalse(torch.isnan(out).any())FMS uses positive ELU+1 kernel feature maps preventing negative denominator explosions.
def test_gpt2_c_attn_split_before_svd(self)-
Expand source code
def test_gpt2_c_attn_split_before_svd(self): """GPT-2 c_attn is split into Q, K, V before SVD rather than factorizing fused matrix.""" orig = FakeGPT2Attention(embed_dim=64) asvd = ASVDAttention(hidden_size=64, num_heads=4, is_decoder=True) asvd.copy_weights(orig) # Ensure query, key, value weights each have Frobenius norm >= 1e-4 for proj in (asvd.query, asvd.key, asvd.value, asvd.out_proj): w = proj.weight if hasattr(proj, "weight") else proj.get_weight() norm = torch.linalg.norm(w.float()).item() self.assertGreater(norm, 1e-4)GPT-2 c_attn is split into Q, K, V before SVD rather than factorizing fused matrix.