Update main.py
Browse files
main.py
CHANGED
|
@@ -1,15 +1,55 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
data = await request.json()
|
| 9 |
-
except:
|
| 10 |
-
data = await request.body()
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
|
| 4 |
+
MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
|
| 5 |
|
| 6 |
+
def main():
|
| 7 |
+
# Load tokenizer
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# Pick dtype Ω
ΩΨ§Ψ³Ψ¨: bfloat16 ΩΩ GPU Ω
ΨͺΨ§ΨΨ ΨΊΩΨ± ΩΨ―Ω float32 ΨΉΩΩ CPU
|
| 11 |
+
has_cuda = torch.cuda.is_available()
|
| 12 |
+
dtype = torch.bfloat16 if has_cuda else torch.float32
|
| 13 |
|
| 14 |
+
# Load model (device_map="auto" ΩΩΨ²ΨΉ ΨͺΩΩΨ§Ψ¦Ω)
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 16 |
+
MODEL_NAME,
|
| 17 |
+
torch_dtype=dtype,
|
| 18 |
+
device_map="auto"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Prompt: explain Past Simple in simple English
|
| 22 |
+
messages = [
|
| 23 |
+
{"role": "system", "content": "You are a friendly English teacher. Explain clearly and simply."},
|
| 24 |
+
{"role": "user", "content": "Explain the Past Simple tense in very simple English. Give rules and 8 short examples. Keep it clear for A2 learners."}
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# Convert chat messages to model input
|
| 28 |
+
text = tokenizer.apply_chat_template(
|
| 29 |
+
messages,
|
| 30 |
+
tokenize=False,
|
| 31 |
+
add_generation_prompt=True
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 35 |
+
|
| 36 |
+
# Generate
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
generated_ids = model.generate(
|
| 39 |
+
**model_inputs,
|
| 40 |
+
max_new_tokens=400,
|
| 41 |
+
do_sample=True,
|
| 42 |
+
temperature=0.7,
|
| 43 |
+
top_p=0.9
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Keep only the newly generated tokens (remove the prompt tokens)
|
| 47 |
+
new_tokens = generated_ids[0, model_inputs["input_ids"].shape[-1]:]
|
| 48 |
+
response = tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 49 |
+
|
| 50 |
+
print("\n=== Model Response ===\n")
|
| 51 |
+
print(response.strip())
|
| 52 |
+
print("\n======================\n")
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
main()
|