KnutJaegersberg commited on
Commit
23a7315
·
verified ·
1 Parent(s): f14a857

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +168 -3
README.md CHANGED
@@ -1,3 +1,168 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - multilingual
5
+ tags:
6
+ - nlp
7
+ base_model: Qwen/Qwen2.5-0.5B
8
+ pipeline_tag: text-generation
9
+ ---
10
+
11
+ # NuExtract-tiny-v1.5 by NuMind 🔥
12
+
13
+ NuExtract-tiny-v1.5 is a fine-tuning of [Qwen/Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B), trained on a private high-quality dataset for structured information extraction. It supports long documents and several languages (English, French, Spanish, German, Portuguese, and Italian).
14
+ To use the model, provide an input text and a JSON template describing the information you need to extract.
15
+
16
+ Note: This model is trained to prioritize pure extraction, so in most cases all text generated by the model is present as is in the original text.
17
+
18
+ We also provide a 3.8B version which is based on Phi-3.5-mini-instruct: [NuExtract-v1.5](https://huggingface.co/numind/NuExtract-v1.5)
19
+
20
+ Check out the [blog post](https://numind.ai/blog/nuextract-1-5---multilingual-infinite-context-still-small-and-better-than-gpt-4o).
21
+
22
+ Try the 3.8B model here: [Playground](https://huggingface.co/spaces/numind/NuExtract-v1.5)
23
+
24
+ ## Benchmark
25
+
26
+ Zero-shot performance (English):
27
+
28
+ <p align="left">
29
+ <img src="english_bench.png" style="width: 600; height: auto;">
30
+ </p>
31
+
32
+ Few-shot fine-tuning:
33
+
34
+ <p align="left">
35
+ <img src="fewshot_bench.png" style="width: 750; height: auto;">
36
+ </p>
37
+
38
+
39
+ ## Usage
40
+
41
+ To use the model:
42
+
43
+ ```python
44
+ import json
45
+ import torch
46
+ from transformers import AutoModelForCausalLM, AutoTokenizer
47
+
48
+ def predict_NuExtract(model, tokenizer, texts, template, batch_size=1, max_length=10_000, max_new_tokens=4_000):
49
+ template = json.dumps(json.loads(template), indent=4)
50
+ prompts = [f"""<|input|>\n### Template:\n{template}\n### Text:\n{text}\n\n<|output|>""" for text in texts]
51
+
52
+ outputs = []
53
+ with torch.no_grad():
54
+ for i in range(0, len(prompts), batch_size):
55
+ batch_prompts = prompts[i:i+batch_size]
56
+ batch_encodings = tokenizer(batch_prompts, return_tensors="pt", truncation=True, padding=True, max_length=max_length).to(model.device)
57
+
58
+ pred_ids = model.generate(**batch_encodings, max_new_tokens=max_new_tokens)
59
+ outputs += tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
60
+
61
+ return [output.split("<|output|>")[1] for output in outputs]
62
+
63
+ model_name = "numind/NuExtract-tiny-v1.5"
64
+ device = "cuda"
65
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, trust_remote_code=True).to(device).eval()
66
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
67
+
68
+ text = """We introduce Mistral 7B, a 7–billion-parameter language model engineered for
69
+ superior performance and efficiency. Mistral 7B outperforms the best open 13B
70
+ model (Llama 2) across all evaluated benchmarks, and the best released 34B
71
+ model (Llama 1) in reasoning, mathematics, and code generation. Our model
72
+ leverages grouped-query attention (GQA) for faster inference, coupled with sliding
73
+ window attention (SWA) to effectively handle sequences of arbitrary length with a
74
+ reduced inference cost. We also provide a model fine-tuned to follow instructions,
75
+ Mistral 7B – Instruct, that surpasses Llama 2 13B – chat model both on human and
76
+ automated benchmarks. Our models are released under the Apache 2.0 license.
77
+ Code: <https://github.com/mistralai/mistral-src>
78
+ Webpage: <https://mistral.ai/news/announcing-mistral-7b/>"""
79
+
80
+ template = """{
81
+ "Model": {
82
+ "Name": "",
83
+ "Number of parameters": "",
84
+ "Number of max token": "",
85
+ "Architecture": []
86
+ },
87
+ "Usage": {
88
+ "Use case": [],
89
+ "Licence": ""
90
+ }
91
+ }"""
92
+
93
+ prediction = predict_NuExtract(model, tokenizer, [text], template)[0]
94
+ print(prediction)
95
+
96
+ ```
97
+
98
+ Sliding window prompting:
99
+
100
+ ```python
101
+ import json
102
+
103
+ MAX_INPUT_SIZE = 20_000
104
+ MAX_NEW_TOKENS = 6000
105
+
106
+ def clean_json_text(text):
107
+ text = text.strip()
108
+ text = text.replace("\#", "#").replace("\&", "&")
109
+ return text
110
+
111
+ def predict_chunk(text, template, current, model, tokenizer):
112
+ current = clean_json_text(current)
113
+
114
+ input_llm = f"<|input|>\n### Template:\n{template}\n### Current:\n{current}\n### Text:\n{text}\n\n<|output|>" + "{"
115
+ input_ids = tokenizer(input_llm, return_tensors="pt", truncation=True, max_length=MAX_INPUT_SIZE).to("cuda")
116
+ output = tokenizer.decode(model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS)[0], skip_special_tokens=True)
117
+
118
+ return clean_json_text(output.split("<|output|>")[1])
119
+
120
+ def split_document(document, window_size, overlap):
121
+ tokens = tokenizer.tokenize(document)
122
+ print(f"\tLength of document: {len(tokens)} tokens")
123
+
124
+ chunks = []
125
+ if len(tokens) > window_size:
126
+ for i in range(0, len(tokens), window_size-overlap):
127
+ print(f"\t{i} to {i + len(tokens[i:i + window_size])}")
128
+ chunk = tokenizer.convert_tokens_to_string(tokens[i:i + window_size])
129
+ chunks.append(chunk)
130
+
131
+ if i + len(tokens[i:i + window_size]) >= len(tokens):
132
+ break
133
+ else:
134
+ chunks.append(document)
135
+ print(f"\tSplit into {len(chunks)} chunks")
136
+
137
+ return chunks
138
+
139
+ def handle_broken_output(pred, prev):
140
+ try:
141
+ if all([(v in ["", []]) for v in json.loads(pred).values()]):
142
+ # if empty json, return previous
143
+ pred = prev
144
+ except:
145
+ # if broken json, return previous
146
+ pred = prev
147
+
148
+ return pred
149
+
150
+ def sliding_window_prediction(text, template, model, tokenizer, window_size=4000, overlap=128):
151
+ # split text into chunks of n tokens
152
+ tokens = tokenizer.tokenize(text)
153
+ chunks = split_document(text, window_size, overlap)
154
+
155
+ # iterate over text chunks
156
+ prev = template
157
+ for i, chunk in enumerate(chunks):
158
+ print(f"Processing chunk {i}...")
159
+ pred = predict_chunk(chunk, template, prev, model, tokenizer)
160
+
161
+ # handle broken output
162
+ pred = handle_broken_output(pred, prev)
163
+
164
+ # iterate
165
+ prev = pred
166
+
167
+ return pred
168
+ ```