feat: add BnB 4-bit quantization strategy + use bf16 model

This commit is contained in:
Christian Medina
2026-07-01 21:14:31 -04:00
parent e56ae5e002
commit 815115e97a
2 changed files with 22 additions and 17 deletions

View File

@@ -35,44 +35,49 @@ def train(config_path):
# Load model - try multiple strategies
print(f"\n[INFO] Loading {config['base_model']}...")
# Strategy 1: bf16 to CPU with low memory usage
print("\n[1/4] Trying: bf16 to CPU...")
# Strategy 1: bf16 model with BnB 4-bit quantization
print("\n[1/4] Trying: bf16 with BnB 4-bit...")
try:
from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
config["base_model"],
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
device_map="cpu",
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True,
)
print("✓ Success: bf16 to CPU")
print("✓ Success: bf16 with BnB 4-bit")
except Exception as e:
print(f"✗ Failed: {e}")
# Strategy 2: 4-bit to CPU
print("\n[2/4] Trying: 4-bit to CPU...")
# Strategy 2: bf16 to CPU
print("\n[2/4] Trying: bf16 to CPU...")
try:
model = AutoModelForCausalLM.from_pretrained(
config["base_model"],
torch_dtype=torch.float16,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
device_map="cpu",
trust_remote_code=True,
)
print("✓ Success: 4-bit to CPU")
print("✓ Success: bf16 to CPU")
except Exception as e:
print(f"✗ Failed: {e}")
# Strategy 3: bf16 auto
print("\n[3/4] Trying: bf16 auto...")
# Strategy 3: 4-bit to CPU
print("\n[3/4] Trying: 4-bit to CPU...")
try:
model = AutoModelForCausalLM.from_pretrained(
config["base_model"],
torch_dtype=torch.bfloat16,
device_map="auto",
low_cpu_mem_usage=True,
torch_dtype=torch.float16,
device_map="cpu",
trust_remote_code=True,
)
print("✓ Success: bf16 auto")
print("✓ Success: 4-bit to CPU")
except Exception as e:
print(f"✗ Failed: {e}")