'''based on transformers'''
import torch
import argparse

from transformers import AutoModelForCausalLM, AutoTokenizer

parse = argparse.ArgumentParser()
parse.add_argument('--model_name_or_path', default="THUDM/glm-4-9b-chat")
parse.add_argument('--device', default="cuda")
parse.add_argument('--query', type=str, default="你好")
args = parse.parse_args()

device = args.device
model_name_or_path = args.model_name_or_path

tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)

query = args.query
inputs = tokenizer.apply_chat_template([{"role": "user", "content": query}],
                                       add_generation_prompt=True,
                                       tokenize=True,
                                       return_tensors="pt",
                                       return_dict=True
                                       )

inputs = inputs.to(device)
model = AutoModelForCausalLM.from_pretrained(
    model_name_or_path,
    torch_dtype=torch.bfloat16,
    low_cpu_mem_usage=True,
    trust_remote_code=True
).to(device).eval()

gen_kwargs = {"max_length": 2500, "do_sample": True, "top_k": 1}
with torch.no_grad():
    outputs = model.generate(**inputs, **gen_kwargs)
    outputs = outputs[:, inputs['input_ids'].shape[1]:]
    print('Result', tokenizer.decode(outputs[0], skip_special_tokens=True))
