Views
No views yet
1import json
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5model_id = "namespace-Pt/ultragist-mistral-7b-inst"
6
7tokenizer = AutoTokenizer.from_pretrained(
8 model_id,
9 trust_remote_code=True,
10)
11model = AutoModelForCausalLM.from_pretrained(
12 model_id,
13 trust_remote_code=True,
14 torch_dtype=torch.bfloat16,
15 attn_implementation="sdpa",
16 # load the entire model on the default gpu
17 device_map={"": "cuda"},
18 # you can manually set the compression ratio, otherwise the model will automatically choose the most suitable compression ratio from [2,4,8,16,32]
19 # ultragist_ratio=[8],
20).eval()
21
22
23with torch.no_grad():
24 # long context
25 with open("data/nqa.json", encoding="utf-8") as f:
26 example = json.load(f)
27 content = f"Read this article:\n\n{example['context']}\n\nNow, answer the question based on the above context.\nQuestion:\n{example['input']}"
28 messages = [{"role": "user", "content": content}]
29 inputs = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda")
30
31 # reset memory before new compression task
32 model.memory.reset()
33
34 # directly call generate to progressively compress the context while generating next tokens
35 outputs = model.generate(**inputs, do_sample=False, top_p=1, temperature=1, max_new_tokens=40)[:, inputs["input_ids"].shape[1]:]
36 print("*"*20)
37 print(f"Input size: {inputs['input_ids'].shape[1]}")
38 print(f"Question: {example['input']}")
39 print(f"Answers: {example['answers']}")
40 print(f"Prediction: {tokenizer.decode(outputs[0], skip_special_tokens=True)}")
41 print("*"*20)
42
43 # extract the compressed memory (including the generated tokens)
44 compressed_memory = model.memory.get_memory()
45 ultragist_size, raw_size, sink_size = model.memory.get_memory_size()
46 print(f"UltraGist size: {ultragist_size}")
47 print(f"Raw size: {raw_size}")
48 print(f"Sink size: {sink_size}")
49 print(f"Memory: {compressed_memory[0][0].shape}")
50 print("*"*20)