|
| 1 | +import json |
| 2 | + |
| 3 | +import pytest |
| 4 | +import torch |
| 5 | + |
| 6 | +from torchao.quantization.quant_api import ( |
| 7 | + Float8WeightOnlyConfig, |
| 8 | + FPXWeightOnlyConfig, |
| 9 | + GemliteUIntXWeightOnlyConfig, |
| 10 | + Int4WeightOnlyConfig, |
| 11 | + Int8WeightOnlyConfig, |
| 12 | + UIntXWeightOnlyConfig, |
| 13 | +) |
| 14 | + |
| 15 | +# Define test configurations as fixtures |
| 16 | +configs = [ |
| 17 | + # Float8DynamicActivationFloat8WeightConfig(), |
| 18 | + Float8WeightOnlyConfig( |
| 19 | + weight_dtype=torch.float8_e4m3fn, |
| 20 | + ), |
| 21 | + UIntXWeightOnlyConfig(dtype=torch.uint1), |
| 22 | + # Int4DynamicActivationInt4WeightConfig(), |
| 23 | + Int4WeightOnlyConfig( |
| 24 | + group_size=32, |
| 25 | + ), |
| 26 | + # Int8DynamicActivationInt4WeightConfig( |
| 27 | + # group_size=64, |
| 28 | + # ), |
| 29 | + # Int8DynamicActivationInt8WeightConfig(), |
| 30 | + Int8WeightOnlyConfig( |
| 31 | + group_size=128, |
| 32 | + ), |
| 33 | + UIntXWeightOnlyConfig( |
| 34 | + dtype=torch.uint3, |
| 35 | + group_size=32, |
| 36 | + use_hqq=True, |
| 37 | + ), |
| 38 | + GemliteUIntXWeightOnlyConfig( |
| 39 | + group_size=128, # Optional, has default of 64 |
| 40 | + bit_width=8, # Optional, has default of 4 |
| 41 | + packing_bitwidth=8, # Optional, has default of 32 |
| 42 | + contiguous=True, # Optional, has default of None |
| 43 | + ), |
| 44 | + FPXWeightOnlyConfig(ebits=4, mbits=8), |
| 45 | + # Float8StaticActivationFloat8WeightConfig( |
| 46 | + # activation_dtype=torch.float8_e4m3fn, |
| 47 | + # weight_dtype=torch.float8_e4m3fn, |
| 48 | + # ), |
| 49 | +] |
| 50 | + |
| 51 | + |
| 52 | +# Create ids for better test naming |
| 53 | +def get_config_ids(configs): |
| 54 | + return [config.__class__.__name__ for config in configs] |
| 55 | + |
| 56 | + |
| 57 | +# Parametrized tests |
| 58 | +@pytest.mark.parametrize("config", configs, ids=get_config_ids) |
| 59 | +def test_to_dict_serialization(config): |
| 60 | + """Test that all configs can be serialized to a dictionary.""" |
| 61 | + # Test to_dict method exists and returns a dict |
| 62 | + assert hasattr( |
| 63 | + config, "to_dict" |
| 64 | + ), f"{config.__class__.__name__} missing to_dict method" |
| 65 | + result = config.to_dict() |
| 66 | + assert isinstance(result, dict) |
| 67 | + |
| 68 | + # Check that all essential attributes are present in the dict |
| 69 | + for attr_name in config.__dict__: |
| 70 | + if not attr_name.startswith("_"): # Skip private attributes |
| 71 | + assert attr_name in result, f"{attr_name} missing in serialized dict" |
| 72 | + |
| 73 | + |
| 74 | +@pytest.mark.parametrize("config", configs, ids=get_config_ids) |
| 75 | +def test_to_json_serialization(config): |
| 76 | + """Test that all configs can be serialized to JSON.""" |
| 77 | + # Test to_json method exists and returns a string |
| 78 | + assert hasattr( |
| 79 | + config, "to_json" |
| 80 | + ), f"{config.__class__.__name__} missing to_json method" |
| 81 | + json_str = config.to_json() |
| 82 | + assert isinstance(json_str, str) |
| 83 | + |
| 84 | + # Verify it's valid JSON |
| 85 | + try: |
| 86 | + parsed = json.loads(json_str) |
| 87 | + assert isinstance(parsed, dict) |
| 88 | + except json.JSONDecodeError as e: |
| 89 | + pytest.fail(f"Invalid JSON for {config.__class__.__name__}: {e}") |
| 90 | + |
| 91 | + |
| 92 | +@pytest.mark.parametrize("config", configs, ids=get_config_ids) |
| 93 | +def test_from_dict_deserialization(config): |
| 94 | + """Test that all configs can be deserialized from a dictionary.""" |
| 95 | + # Get the class of the instance |
| 96 | + cls = config.__class__ |
| 97 | + |
| 98 | + # Serialize to dict |
| 99 | + data = config.to_dict() |
| 100 | + |
| 101 | + # Test from_dict class method exists |
| 102 | + assert hasattr(cls, "from_dict"), f"{cls.__name__} missing from_dict class method" |
| 103 | + |
| 104 | + # Deserialize back to instance |
| 105 | + deserialized = cls.from_dict(data) |
| 106 | + |
| 107 | + # Check it's the right class |
| 108 | + assert isinstance(deserialized, cls) |
| 109 | + |
| 110 | + # Compare key attributes |
| 111 | + for attr_name in config.__dict__: |
| 112 | + if not attr_name.startswith("_"): # Skip private attributes |
| 113 | + original_value = getattr(config, attr_name) |
| 114 | + deserialized_value = getattr(deserialized, attr_name) |
| 115 | + |
| 116 | + # Special handling for torch dtypes |
| 117 | + if ( |
| 118 | + hasattr(original_value, "__module__") |
| 119 | + and original_value.__module__ == "torch" |
| 120 | + ): |
| 121 | + assert str(original_value) == str( |
| 122 | + deserialized_value |
| 123 | + ), f"Attribute {attr_name} mismatch for {cls.__name__}" |
| 124 | + else: |
| 125 | + assert ( |
| 126 | + original_value == deserialized_value |
| 127 | + ), f"Attribute {attr_name} mismatch for {cls.__name__}" |
| 128 | + |
| 129 | + |
| 130 | +@pytest.mark.parametrize("config", configs, ids=get_config_ids) |
| 131 | +def test_from_json_deserialization(config): |
| 132 | + """Test that all configs can be deserialized from JSON.""" |
| 133 | + # Get the class of the instance |
| 134 | + cls = config.__class__ |
| 135 | + |
| 136 | + # Serialize to JSON |
| 137 | + json_str = config.to_json() |
| 138 | + |
| 139 | + # Test from_json class method exists |
| 140 | + assert hasattr(cls, "from_json"), f"{cls.__name__} missing from_json class method" |
| 141 | + |
| 142 | + # Deserialize back to instance |
| 143 | + deserialized = cls.from_json(json_str) |
| 144 | + |
| 145 | + # Check it's the right class |
| 146 | + assert isinstance(deserialized, cls) |
| 147 | + |
| 148 | + # Verify the instance is equivalent to the original |
| 149 | + # This assumes __eq__ is properly implemented |
| 150 | + assert ( |
| 151 | + config == deserialized |
| 152 | + ), f"Deserialized instance doesn't match original for {cls.__name__}" |
| 153 | + |
| 154 | + |
| 155 | +@pytest.mark.parametrize("config", configs, ids=get_config_ids) |
| 156 | +def test_round_trip_equivalence(config): |
| 157 | + """Test complete serialization and deserialization round trip.""" |
| 158 | + # JSON round trip |
| 159 | + json_str = config.to_json() |
| 160 | + deserialized_from_json = config.__class__.from_json(json_str) |
| 161 | + assert ( |
| 162 | + config == deserialized_from_json |
| 163 | + ), f"JSON round trip failed for {config.__class__.__name__}" |
| 164 | + |
| 165 | + # Dict round trip |
| 166 | + data_dict = config.to_dict() |
| 167 | + deserialized_from_dict = config.__class__.from_dict(data_dict) |
| 168 | + assert ( |
| 169 | + config == deserialized_from_dict |
| 170 | + ), f"Dict round trip failed for {config.__class__.__name__}" |
0 commit comments