Views
No views yet
transformers library v4.30.0+peft library v0.3.0+pip install torch transformers peft1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from peft import PeftModel
4
5# 1) Select device (GPU if available)
6device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
8# 2) Define model identifiers
9BASE_MODEL = "EleutherAI/gpt-neo-2.7B"
10ADAPTER_REPO = "DumbsterDrekk/hindi-gpt-neo-2.7B"
11
12# 3) Load the base model in FP16 and move it to the selected device
13base_model = AutoModelForCausalLM.from_pretrained(
14 BASE_MODEL,
15 torch_dtype=torch.float16,
16 device_map="auto",
17)
18base_model.to(device)
19base_model.config.use_cache = True
20
21# 4) Load the LoRA adapter from the Hub and merge it with the base model
22model = PeftModel.from_pretrained(
23 base_model,
24 ADAPTER_REPO,
25 torch_dtype=torch.float16,
26 device_map="auto",
27 use_auth_token=True, # if repository is private
28)
29
30# 5) Load the tokenizer (uses adapter repo to pick up special tokens/config)
31tokenizer = AutoTokenizer.from_pretrained(
32 ADAPTER_REPO,
33 trust_remote_code=True
34)
35
36# 6) Perform inference with the LoRA-adapted model
37prompt = "भारत एक महान राष्ट्र है क्योंकि"
38inputs = tokenizer(prompt, return_tensors="pt").to(device)
39outputs = model.generate(**inputs, max_new_tokens=50)
40print(tokenizer.decode(outputs[0], skip_special_tokens=True))BASE_MODEL is the pre-trained checkpoint; ADAPTER_REPO is the Hugging Face repo containing the LoRA adapter.torch.float16) for reduced memory usage.device_map="auto" splits the model across GPUs if multiple are present.use_cache=True enables faster generation by caching key/value states.PeftModel.from_pretrained wraps the base model with the LoRA weights from ADAPTER_REPO.use_auth_token=True is needed if the repo is private.