fix: load 4-bit model with device_map=auto (let transformers distribute)

This commit is contained in:
Christian Medina
2026-07-02 19:33:37 -04:00
parent 20626e7a78
commit a0f4f644b0

View File

@@ -33,55 +33,22 @@ def train(config_path):
print(f"Loading model: {config['base_model']}") print(f"Loading model: {config['base_model']}")
# Load bf16 model to CPU # Load 4-bit model directly (already quantized on disk)
print(f"\n[INFO] Loading {config['base_model']} bf16 to CPU...") print(f"\n[INFO] Loading {config['base_model']} (4-bit)...")
model = AutoModelForCausalLM.from_pretrained( model = AutoModelForCausalLM.from_pretrained(
config["base_model"], config["base_model"],
device_map="cpu", device_map="auto", # Let transformers distribute
torch_dtype=torch.bfloat16, torch_dtype=torch.float16,
trust_remote_code=True, trust_remote_code=True,
low_cpu_mem_usage=True, low_cpu_mem_usage=True,
) )
print("✓ Model loaded to CPU (~70GB bf16)") print(" Success: Model loaded")
# Apply PEFT k-bit training preparation # Check memory usage
print(" Applying PEFT k-bit preparation...") for i in range(torch.cuda.device_count()):
from peft import prepare_model_for_kbit_training mem = torch.cuda.memory_allocated(i) / 1e9
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False) total = torch.cuda.get_device_properties(i).total_memory / 1e9
print(" ✓ Model prepared for k-bit training") print(f" GPU {i}: {mem:.2f} GB / {total:.2f} GB")
# Manually quantize linear layers
print(" Quantizing linear layers to 4-bit...")
from bitsandbytes.nn import Linear4bit
from torch import nn
quantized_count = 0
for name, module in model.named_modules():
if isinstance(module, nn.Linear) and 'lm_head' not in name:
new_module = Linear4bit(
module.in_features,
module.out_features,
bias=module.bias is not None,
)
new_module.weight = nn.Parameter(module.weight.data.clone())
if module.bias is not None:
new_module.bias = nn.Parameter(module.bias.data.clone())
layers = name.split('.')
parent = model
for layer in layers[:-1]:
parent = getattr(parent, layer)
setattr(parent, layers[-1], new_module)
quantized_count += 1
print(f" ✓ Quantized {quantized_count} linear layers to 4-bit")
# Move to GPU
print(" Moving to GPU 0...")
model = model.to("cuda:0")
print("✓ Success: Model loaded to GPU 0 (4-bit)")
print(f" GPU 0: {torch.cuda.memory_allocated(0) / 1e9:.2f} GB")
print(f" Free VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9 - torch.cuda.memory_allocated(0) / 1e9:.2f} GB")
# Add LoRA # Add LoRA
lora_config = LoraConfig( lora_config = LoraConfig(