Views
No views yet
pip install transformers peft torch jsonlines tqdm.jsonl, where each line has the field passage_text:1{
2 "id": "id-123",
3 "passage_text": "Lorem ipsum dolor sit amet..."
4}"summary_text"1from peft import PeftModel
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4import jsonlines
5from tqdm import tqdm
6import json
7import copy
8import argparse
9
10torch.random.manual_seed(0)
11
12def main(model_id, peft_model, max_length, input_filepath, output_filepath):
13
14 assert torch.cuda.is_available(), "This model needs a GPU to run ..."
15 device = 'cuda'
16
17 tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
18
19 if model_id == "google/gemma-2-2b-it" or (model_id.startswith("/") and model_id.split("/")[-1].startswith("gemma")):
20 print(f"model_id: {model_id}\t torch_dtype=torch.bfloat16")
21 model = AutoModelForCausalLM.from_pretrained(
22 model_id,
23 torch_dtype=torch.bfloat16,
24 trust_remote_code=True,
25 device_map="auto"
26 )
27 else:
28 print(f"model_id: {model_id}\t torch_dtype=torch.auto, flash_attention_2")
29 model = AutoModelForCausalLM.from_pretrained(
30 model_id,
31 torch_dtype="auto",
32 trust_remote_code=True,
33 attn_implementation="flash_attention_2",
34 device_map="auto"
35 )
36
37 if len(peft_model) > 0:
38 finetuned_model = PeftModel.from_pretrained(
39 model,
40 peft_model,
41 torch_dtype=torch.float16,
42 is_trainable=False,
43 device_map="auto"
44 )
45 finetuned_model = finetuned_model.merge_and_unload()
46 else:
47 finetuned_model = model
48
49 input_lines = []
50 with jsonlines.open(input_filepath) as f:
51 for line in f.iter():
52 input_lines.append(line)
53
54 output_lines = []
55 for line in tqdm(input_lines):
56 messages = [
57 {
58 "role": "user",
59 "content": f"Summarize the following content.\nContent:\n{line['passage_text']}\nSummary:"
60 },
61 ]
62
63 inputs = tokenizer.apply_chat_template(
64 messages,
65 add_generation_prompt=True,
66 return_tensors="pt",
67 max_length=max_length
68 ).to(device)
69
70 output_json = copy.deepcopy(line)
71
72 try:
73 outputs = finetuned_model.generate(
74 inputs,
75 max_new_tokens=512,
76 do_sample=False,
77 num_return_sequences=1,
78 eos_token_id=tokenizer.eos_token_id,
79 use_cache=False
80 )
81
82 sample_output = outputs[0]
83 decoded_text = tokenizer.decode(sample_output[len(inputs[0]):], skip_special_tokens=True)
84 output_json['summary_text'] = decoded_text
85
86 except Exception as e:
87 print(e)
88 output_json['summary_text'] = ''
89
90 output_lines.append(output_json)
91
92 with open(output_filepath, 'w') as f:
93 for line in output_lines:
94 json.dump(line, f)
95 f.write('\n')
96
97if __name__ == '__main__':
98 parser = argparse.ArgumentParser()
99 parser.add_argument("--model_id", default="microsoft/Phi-3-mini-4k-instruct")
100 parser.add_argument("--peft_model", default="")
101 parser.add_argument("--max_length", default=2048)
102 parser.add_argument("--input_filepath")
103 parser.add_argument("--output_filepath")
104
105 args = parser.parse_args()
106 main(args.model_id, args.peft_model, args.max_length, args.input_filepath, args.output_filepath)1python main.py \
2 --model_id "iaminju/CoLoR-Phi-3-mini-4k-instruct" \
3 --max_length 20000 \
4 --input_filepath "/path/to/input.jsonl" \
5 --output_filepath "/path/to/output.jsonl"@inproceedings{Seo2025CoLoR,
author = {Minju Seo and
Jinheon Baek and
Seongyun Lee and
Sung Ju Hwang},
editor = {Wanxiang Che and
Joyce Nabende and
Ekaterina Shutova and
Mohammad Taher Pilehvar},
title = {Efficient Long Context Language Model Retrieval with Compression},
booktitle = {Proceedings of the 63rd Annual Meeting of the Association for Computational
Linguistics (Volume 1: Long Papers), {ACL} 2025, Vienna, Austria,
July 27 - August 1, 2025},
pages = {15251--15268},
publisher = {Association for Computational Linguistics},
year = {2025},
url = {https://aclanthology.org/2025.acl-long.740/},
timestamp = {Wed, 24 Sep 2025 15:22:07 +0200},
biburl = {https://dblp.org/rec/conf/acl/SeoBLH25.bib},
bibsource = {dblp computer science bibliography, https://dblp.org}
}