lbourdois commited on
Commit
68cb00b
·
verified ·
1 Parent(s): df52efb

Improve language tag

Browse files

Hi! As the model is multilingual, this is a PR to add other languages than English to the language tag to improve the referencing. Note that 29 languages are announced in the README, but only 13 are explicitly listed. I was therefore only able to add these 13 languages.

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