File size: 1,762 Bytes
f0ea2dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
MODEL_ID = "ibm-granite/granite-4.0-micro"
CHECKPOINTS = {
"Base model": None,
"LoRA checkpoint-30": "./lora-out/checkpoint-30",
"LoRA checkpoint-60": "./lora-out/checkpoint-60",
"LoRA checkpoint-90": "./lora-out/checkpoint-90",
"LoRA checkpoint-120": "./lora-out/checkpoint-120",
}
MAX_NEW_TOKENS = 300
def load_model(checkpoint_path=None):
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
dtype=torch.float16,
device_map="cuda"
)
if checkpoint_path is not None:
model = PeftModel.from_pretrained(model, checkpoint_path)
model.eval()
return model
def generate_answer(model, tokenizer, question):
prompt = f"Frage:\n{question}\n\nAntwort:\n"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
output = model.generate(
**inputs,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=False, # deterministisch
)
text = tokenizer.decode(output[0], skip_special_tokens=True)
return text[len(prompt):].strip()
def main():
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
print("=" * 80)
question = input("Bitte eine Frage eingeben:\n> ").strip()
print("=" * 80)
for label, checkpoint in CHECKPOINTS.items():
print(f"\n=== {label} ===\n")
model = load_model(checkpoint)
answer = generate_answer(model, tokenizer, question)
print(answer)
print("\n" + "-" * 80)
# Speicher sauber freigeben (optional, aber sauber)
del model
torch.cuda.empty_cache()
if __name__ == "__main__":
main()
|