Module neuralops.tests.test_hybrid_freeze
Unit tests for strict parameter freezing on hybrid recurrent attention modules and trainable parameter count thresholds.
Classes
class Dummy12LayerHybridModel (d_model: int = 256, lora_rank: int = 16)-
Expand source code
class Dummy12LayerHybridModel(nn.Module): def __init__(self, d_model: int = 256, lora_rank: int = 16): super().__init__() self.layers = nn.ModuleList([ DummyRecurrentModule(d_model=d_model, lora_rank=lora_rank) for _ in range(12) ]) self.classifier = nn.Linear(d_model, 2)Base 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 DummyRecurrentModule (d_model: int = 64, lora_rank: int = 16)-
Expand source code
class DummyRecurrentModule(nn.Module): def __init__(self, d_model: int = 64, lora_rank: int = 16): super().__init__() self.d_model = d_model self.lora_rank = lora_rank self.q_proj = LoRALinear(d_model, d_model, lora_rank=lora_rank, freeze_base=True) self.k_proj = LoRALinear(d_model, d_model, lora_rank=lora_rank, freeze_base=True) self.v_proj = LoRALinear(d_model, d_model, lora_rank=lora_rank, freeze_base=True) self.out_proj = LoRALinear(d_model, d_model, lora_rank=lora_rank, freeze_base=True) self.beta = nn.Linear(d_model, 4) self.alpha = nn.Linear(d_model, 4)Base 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 TestHybridFreeze (methodName='runTest')-
Expand source code
class TestHybridFreeze(unittest.TestCase): def test_freeze_hybrid_only_lora(self): """Verify that in recurrent/hybrid modules only LoRA adapters (and classifier heads) are trainable.""" model = Dummy12LayerHybridModel(d_model=256, lora_rank=16) trainable_params = get_recovery_params(model) trainable_names = [name for name, p in model.named_parameters() if p.requires_grad] for name in trainable_names: if "classifier" in name: continue self.assertTrue( "lora_a" in name.lower() or "lora_b" in name.lower(), f"Parameter '{name}' should be frozen but is trainable!" ) total_trainable = sum(p.numel() for p in trainable_params) self.assertLess(total_trainable, 3_000_000, f"Expected < 3M trainable params, got {total_trainable}") def test_oom_warning_on_large_params(self): """Simulate a model with > 5M trainable parameters and verify safety reduction.""" # Create modules with large linear layers so total trainable params exceeds 5,000,000 # 10 layers * (4096*64 + 4096*64) = 10 * 524,288 = 5,242,880 params layers = [LoRALinear(4096, 4096, lora_rank=64, freeze_base=False) for _ in range(10)] model = nn.Sequential(*layers) params = get_recovery_params(model) # Verify that lora_rank was automatically reduced to 8 for m in model.modules(): if hasattr(m, "lora_rank") and isinstance(m, LoRALinear): self.assertLessEqual(m.lora_rank, 8)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_freeze_hybrid_only_lora(self)-
Expand source code
def test_freeze_hybrid_only_lora(self): """Verify that in recurrent/hybrid modules only LoRA adapters (and classifier heads) are trainable.""" model = Dummy12LayerHybridModel(d_model=256, lora_rank=16) trainable_params = get_recovery_params(model) trainable_names = [name for name, p in model.named_parameters() if p.requires_grad] for name in trainable_names: if "classifier" in name: continue self.assertTrue( "lora_a" in name.lower() or "lora_b" in name.lower(), f"Parameter '{name}' should be frozen but is trainable!" ) total_trainable = sum(p.numel() for p in trainable_params) self.assertLess(total_trainable, 3_000_000, f"Expected < 3M trainable params, got {total_trainable}")Verify that in recurrent/hybrid modules only LoRA adapters (and classifier heads) are trainable.
def test_oom_warning_on_large_params(self)-
Expand source code
def test_oom_warning_on_large_params(self): """Simulate a model with > 5M trainable parameters and verify safety reduction.""" # Create modules with large linear layers so total trainable params exceeds 5,000,000 # 10 layers * (4096*64 + 4096*64) = 10 * 524,288 = 5,242,880 params layers = [LoRALinear(4096, 4096, lora_rank=64, freeze_base=False) for _ in range(10)] model = nn.Sequential(*layers) params = get_recovery_params(model) # Verify that lora_rank was automatically reduced to 8 for m in model.modules(): if hasattr(m, "lora_rank") and isinstance(m, LoRALinear): self.assertLessEqual(m.lora_rank, 8)Simulate a model with > 5M trainable parameters and verify safety reduction.