File size: 26,492 Bytes
a975439 2676b9e 9833549 2676b9e 2442ac6 2676b9e 2442ac6 2676b9e 2442ac6 2676b9e a975439 2676b9e a975439 2676b9e a975439 2676b9e a975439 2676b9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 |
---
license: apache-2.0
language:
- en
base_model:
- >-
MasterControlAIML/DeepSeek-R1-Strategy-Qwen-2.5-1.5b-Unstructured-To-Structured
tags:
- DeepSeek
- R1
- SFT
- Qwen
- JSON
- Unstructured
- Structured
---
# MasterControlAIML R1-Qwen2.5-1.5b SFT R1 JSON Unstructured-To-Structured Model
[](https://github.com/unslothai/unsloth)
This repository provides a fine-tuned Qwen2 model optimized for transforming unstructured text into structured JSON outputs according to a predefined schema. The model is finetuned from the base model **MasterControlAIML/DeepSeek-R1-Strategy-Qwen-2.5-1.5b-Unstructured-To-Structured** and leverages LoRA techniques for efficient adaptation.
> **Key Highlights:**
>
> - **Developed by:** [MasterControl]()
> - **License:** [Apache-2.0](LICENSE)
> - **Finetuned from:** `MasterControlAIML/DeepSeek-R1-Strategy-Qwen-2.5-1.5b-Unstructured-To-Structured`
> - **Accelerated Training:** Achieved 2x faster training using [Unsloth](https://github.com/unslothai/unsloth) and Hugging Face's TRL library.
---
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Using Unsloth for Fast Inference](#using-unsloth-for-fast-inference)
- [Using Transformers for Inference](#using-transformers-for-inference)
- [Prompt & Code Example - How to run](#prompt--code-example)
- [Example: Advanced Data Extraction with LangChain](#example-advanced-data-extraction-with-langchain)
- [Sample Responses & Chain-of-Thought Explanations](#sample-responses--chain-of-thought-explanations)
- [Contributing](#contributing)
- [License](#license)
- [Acknowledgments](#acknowledgments)
---
## Overview
This model is tailored for tasks where mapping unstructured text (e.g., manuals, QA documents) into a structured JSON format is required. It supports hierarchical data extraction based on a given JSON Schema, ensuring that the generated outputs follow the exact structure and rules defined by the schema.
---
## Features
- **Efficient Inference:** Utilizes the [Unsloth](https://github.com/unslothai/unsloth) library for fast model inference.
- **Structured Output:** Maps text inputs into a strict JSON schema with hierarchical relationships.
- **Flexible Integration:** Example code snippets show how to use both the Unsloth API and Hugging Face’s Transformers.
- **Advanced Prompting:** Detailed examples using the Alpaca prompt template and LangChain prompt templates are provided below.
---
## Installation
### Prerequisites
- **Python:** 3.8+
- **PyTorch:** (Preferably with CUDA support)
- **Required Libraries:** `transformers`, `torch`, `unsloth`, `langchain` (for advanced usage)
### Installation Command
Install the required Python packages with:
```bash
pip install torch transformers unsloth langchain
```
---
## Quick Start
### Using Unsloth for Fast Inference
The Unsloth library allows you to quickly load and run inference with the model. Below is a basic example:
```python
from unsloth import FastLanguageModel
import torch
MODEL = "MasterControlAIML/DeepSeek-R1-Qwen2.5-1.5b-SFT-R1-JSON-Unstructured-To-Structured-lora"
# Load model and tokenizer
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=MODEL,
max_seq_length=2048,
dtype=None,
load_in_4bit=False,
)
# Prepare for inference
FastLanguageModel.for_inference(model)
ALPACA_PROMPT = """
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Response:
{}
"""
# Example instruction and prompt
instruction = "" (see examples below)
prompt = ALPACA_PROMPT.format(instruction, "")
inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
output = model.generate(**inputs, max_new_tokens=2000)
# Print generated text
print(tokenizer.batch_decode(output, skip_special_tokens=True)[0])
```
---
### Using Transformers for Inference
Alternatively, you can use Hugging Face's Transformers directly:
```python
from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
import torch
MODEL = "MasterControlAIML/DeepSeek-R1-Qwen2.5-1.5b-SFT-R1-JSON-Unstructured-To-Structured-lora"
# Initialize tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.float16, device_map="auto")
ALPACA_PROMPT = """
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Response:
{}
"""
TEXT = ""(see examples below)
prompt = ALPACA_PROMPT.format(TEXT, "")
inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
text_streamer = TextStreamer(tokenizer)
with torch.no_grad():
output_ids = model.generate(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
max_new_tokens=2000,
temperature=0.7,
top_p=0.9,
repetition_penalty=1.1,
streamer=text_streamer,
pad_token_id=tokenizer.pad_token_id,
)
print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
```
---
## Prompt & Code Example
### Example: Advanced Data Extraction with LangChain
#### Code
```python
from langchain_core.prompts import PromptTemplate
# Sample text input with a slightly different structure
TEXT1 = """
Quality Assurance Manual Overview
This document provides an introduction to the quality assurance procedures for manufacturing processes.
## Introduction to Manufacturing Processes
This section covers the basics of manufacturing processes. It includes definitions and a brief history.
| Name | Description |
|---------------------|---------------------------|
| Process 1 | Initial process in制造过程。|
### Detailed Process 1
This process refines material to meet specific standards.
| Parameter | Range |
|-----------|----------|
| Temperature | 200-300°C |
**Operational Parameters**
The operational parameters are critical for the success of this process.
| Setting | Class |
|---------|------------|
| Critical | High Precision |
"""
# A different JSON schema example
SCHEMA1 = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Dot-separated integers representing the hierarchical id of the element."
},
"title": {
"type": "string",
"description": "Descriptive title of the section or component."
},
"level": {
"type": "integer",
"description": "Hierarchy level starting from 0 for the root."
},
"level_type": {
"type": "string",
"enum": ["ROOT", "SECTION", "SUBSECTION", "DETAIL_N"],
"description": "Type of the hierarchal level."
},
"component": {
"type": "array",
"items": {
"type": "object",
"properties": {
"idc": {
"type": "integer",
"description": "Sequential unique component ID."
},
"component_type": {
"type": "string",
"enum": ["PARAGRAPH", "TABLE", "CALCULATION", "CHECKBOX"],
"description": "Type of the component."
},
"metadata": {
"type": "string",
"description": "Additional metadata token (may be <title>, <note>, or <overview>)."
},
"properties": {
"type": "object",
"properties": {
"variables": {
"type": "array",
"items": {
"type": "object",
"properties": {
"idx": {
"type": "string",
"description": "Unique identifier, X.Y (X represents row, Y represents column for Tables, 0 otherwise)."
},
"name": {
"type": "string",
"description": "Attribute name."
},
"value": {
"type": "string",
"description": "Attribute value."
},
"unit": {
"type": "string",
"description": "Optional unit."
},
"metrics": {
"type": "boolean",
"description": "Flag indicating if variable is a metric."
},
"formula": {
"type": "boolean",
"description": "Flag indicating if variable has an equation."
}
}
}
},
"content": {
"type": "array",
"items": {
"type": "string"
},
"description": "Text content (e.g., notes, MCQs, questions, points, etc.)."
}
}
}
}
}
},
"children": {
"type": "array",
"items": {
"$ref": "#"
},
"description": "Nested elements."
}
},
"required": ["id", "title", "level", "level_type", "component", "children"]
}
"""
# LangChain prompt to guide the model
SYSTEM_PROMPT = """
### Role:
You are an expert data extractor specializing in mapping hierarchical text data into a given JSON Schema.
### DATA INPUT:
- **Text:** ```{TEXT}```
- **Blank JSON Schema:** ```{SCHEMA}```
### TASK REQUIREMENT:
1. Analyze the given text and map all relevant information strictly into the provided JSON Schema.
2. Provide your output in **two mandatory sections**:
- **`<answer>`:** The filled JSON object
- **`<think>`:** Reasoning for the mapping decisions
### OUTPUT STRUCTURE:
`<think> /* Explanation of mapping logic */ </think>`
`<answer> /* Completed JSON Object */ </answer>`
### STRICT RULES FOR GENERATING OUTPUT:
1. **Both Tags Required:**
- Always provide both the `<think>` and `<answer>` sections.
- If reasoning is minimal, state: "Direct mapping from text to schema."
2. **JSON Schema Mapping:**
- Strictly map the text data to the given JSON Schema without modification or omissions.
3. **Hierarchy Preservation:**
- Maintain proper parent-child relationships and follow the schema's hierarchical structure.
4. **Correct Mapping of Attributes:**
- Map key attributes, including `id`, `idc`, `idx`, `level_type`, and `component_type`.
5. **JSON Format Compliance:**
- Escape quotes (`\"`), replace newlines with `\\n`, avoid trailing commas, and use double quotes exclusively.
6. **Step-by-Step Reasoning:**
- Explain your reasoning within the `<think>` tag.
### IMPORTANT:
If either the `<think>` or `<answer>` tags is missing, the response will be considered incomplete.
"""
from langchain_core.prompts import PromptTemplate
system_prompt_template = PromptTemplate(template=SYSTEM_PROMPT, input_variables=["TEXT", "SCHEMA"])
# Format the prompt with your chosen text and JSON schema
system_prompt_str = system_prompt_template.format(TEXT=TEXT1, SCHEMA=SCHEMA1)
# Now, pass `system_prompt_str` into your model inference pipeline (using Unsloth, Transformers, etc.)
# to get the output that contains both the reasoning and the mapped JSON object.
```
---
## Sample Responses & Chain-of-Thought Explanations
Below are two sample outputs that include both a **Chain-of-Thought Explanation** (`<think>`) and the corresponding **Filled JSON Schema** (`<answer>`). These examples show how the model should articulate its reasoning and produce the final mapped schema.
### Sample Response 1
```plaintext
<think>
Chain of Thought Explanation:
To fill out the blank schema based on the Text and make it look exactly like the Filled Schema, I would start by understanding what each part represents.
First, looking at the Blank Schema, it has placeholders where actual content should go. The goal here is to replace those placeholders with appropriate data extracted from the Text so that when completed, it matches the Filled Schema perfectly.
I notice that both schemas have a similar structure, just with different types of components. My first step would be to identify how each component type maps back to elements in the Text.
For example, in the Introduction section under "Key Metrics," there's a table listing two variables: Defect Rate at 0.5% and Yield Rate at 98%. In the Filled Schema, these become entries in the 'variables' array of a Table component. So I'd extract these values from the corresponding parts in the Text and plug them into their respective places in the Blank Schema.
Next, moving down to the Subsection titled "QA Checklists," there are checkboxes for Confirmations about defects being identified and corrected versus audits conducted regularly. Looking at the Text again, I see bullet points describing whether particular checks were done—like confirming if defects had been found—and then noting what wasn't confirmed. From this, I can infer that each checkbox corresponds to one of these confirmation statements.
Then comes the Detail Section called "Standards Overview." Here, there's another table comparing ISO 9001 and ASQ-Certified QM. In the Text, under QA Standards Comparison, they mention checking both options with clear indicators of true/false states. Therefore, I'd replicate this structure in the Blank Schema by adding these same rows of comparison details.
Throughout this entire process, my focus remains on matching each piece of textual information to its correct location within the schema without altering any other parts beyond what's specified. By methodically identifying and populating each placeholder based on the Text's content, the end result should mirror the Filled Schema precisely because every element in the filled version was accounted for during extraction.
</think>
<answer>{
"id": "0.0",
"title": "Quality Assurance Manual for Manufacturing Process",
"level": 0,
"level_type": "ROOT",
"component": [
{
"idc": 0,
"component_type": "PARAGRAPH",
"metadata": "<overview>This manual covers the QA procedures and guidelines for various manufacturing processes.</overview>",
"properties": {
"variables": [],
"content": []
}
}
],
"children": [
{
"id": "1.0",
"title": "Introduction to Quality Assurance",
"level": 1,
"level_type": "SECTION",
"component": [
{
"idc": 0,
"component_type": "PARAGRAPH",
"metadata": "",
"properties": {
"variables": [],
"content": [
"Quality Assurance (QA) involves systematic activities designed to ensure consistent production of reliable and safe products.",
"It aims to reduce variability in the final product and improve overall efficiency."
]
}
},
{
"idc": 1,
"component_type": "TABLE",
"metadata": "",
"properties": {
"variables": [
{
"idx": "0.0",
"name": "Metric",
"value": "Defect Rate",
"unit": "%",
"metrics": true,
"formula": false
},
{
"idx": "0.1",
"name": "Target",
"value": 0.5,
"unit": null,
"metrics": true,
"formula": false
}
],
"content": []
}
}
],
"children": [
{
"id": "1.1",
"title": "QA in Manufacturing Processes",
"level": 2,
"level_type": "SUBSECTION",
"component": [
{
"idc": 0,
"component_type": "PARAGRAPH",
"metadata": "",
"properties": {
"variables": [],
"content": [
"Manufacturing processes require strict adherence to QA procedures to ensure product reliability and safety."
]
}
},
{
"idc": 1,
"component_type": "CHECKBOX",
"metadata": "",
"properties": {
"variables": [
{
"idx": "0.0",
"name": "Process Control",
"value": true,
"unit": null,
"metrics": false,
"formula": false
},
{
"idx": "0.1",
"name": "Raw Material Inspection",
"value": false,
"unit": null,
"metrics": false,
"formula": false
}
],
"content": [
"Check if the following QA procedures are followed:",
"\u2713 Process Control \u2713 Raw Material Inspection"
]
}
}
],
"children": [
{
"id": "1.1.1",
"title": "Standard QA Practices",
"level": 3,
"level_type": "DETAIL_N",
"component": [
{
"idc": 0,
"component_type": "PARAGRAPH",
"metadata": "",
"properties": {
"variables": [],
"content": [
"Adherence to ISO 9001 standards helps maintain quality control."
]
}
},
{
"idc": 1,
"component_type": "TABLE",
"metadata": "",
"properties": {
"variables": [
{
"idx": "0.0",
"name": "Comparison",
"value": "ISO 9001 vs ASQ-Certified QM",
"unit": null,
"metrics": false,
"formula": false
}
],
"content": []
}
}
],
"children": []
}
]
}
]
}
]
}</answer>
```
---
### Sample Response 2
```plaintext
<think>
Chain of Thought Explanation:
To fill out the blank schema based on the provided Text and ensure it matches exactly what's in the Filled Schema, we can proceed step by step as follows:
1. **Identify Components**: Recognize that both schemas contain similar structures with varying component types (Table, Paragraph, Checkbox).
2. **Extract Data from Text**:
- Locate tables containing variables like Defect Rate and Yield Rate in the introduction section.
- Identify confirmatory statements regarding defect identification and regular audits in sub-sections.
3. **Populate Variables**: Fill the Table component under "Key Metrics" with extracted variable names and values (Defect Rate=0.5%, Yield Rate=98%).
4. **Fill Checkboxes**: Convert bullet points into boolean values for checkboxes; set Confirmations to reflect findings (true for defects found, false for audits missed).
5. **Add Standards Table**: Create a second Table in the Details section comparing ISO 9001 and ASQ-Certified QM, mirroring the original.
By meticulously aligning each extracted detail with its designated spot in the Blank Schema, ensuring no additional or omitted data exists, the resulting schema will exactly match the Filled Schema's structure and content.
**Cross Verification**: Each action directly corresponds to filling specific fields without deviation. Thus, following this structured approach ensures identical outcomes between the transformed schema and the target Filled Schema.
</think>
<answer>{
"id": "0.0",
"title": "Quality Assurance Manual",
"level": 0,
"level_type": "ROOT",
"component": [
{
"idc": 0
},
{
"idc": 1
}
],
"children": [
{
"id": "1.0",
"title": "Introduction to Manufacturing Processes",
"level": 1,
"level_type": "SECTION",
"component": [],
"children": [
{
"id": "1.1",
"title": "Detailed Process 1",
"level": 2,
"level_type": "SUBSECTION",
"component": [],
"children": []
},
{
"id": "1.2",
"title": "Operational Details",
"level": 2,
"level_type": "SUBSECTION",
"component": [
{
"idc": 0,
"component_type": "PARAGRAPH",
"metadata": "<overview>This section outlines the operational aspects of Process 1.</overview>",
"properties": {}
}
],
"children": []
}
]
},
{
"id": "2.0",
"title": "Advanced Manufacturing Techniques",
"level": 1,
"level_type": "SECTION",
"component": [],
"children": [
{
"id": "2.1",
"title": "High-Temperature Processing",
"level": 2,
"level_type": "SUBSECTION",
"component": [
{
"idc": 0,
"component_type": "TABLE",
"metadata": "<title>Table of Specifications</title>",
"properties": {
"variables": [
{
"idx": "0.0",
"name": "Parameter",
"value": "Temperature",
"unit": "\u00b0C",
"metrics": true,
"formula": false
},
{
"idx": "1.0",
"name": "Range",
"value": "[200, 300]",
"unit": null,
"metrics": false,
"formula": false
}
],
"content": [
"Note: Ensure temperature control within specified range."
]
}
}
],
"children": []
}
]
}
]
}</answer>
```
---
## Contributing
Contributions, bug reports, and feature requests are welcome! Please open an issue or submit a pull request if you would like to contribute to this project.
---
## License
This project is licensed under the [Apache-2.0 License](LICENSE).
---
## Acknowledgments
- **Unsloth:** For providing fast model inference capabilities. ([GitHub](https://github.com/unslothai/unsloth))
- **Hugging Face:** For the [Transformers](https://github.com/huggingface/transformers) and [TRL](https://github.com/huggingface/trl) libraries.
- **LangChain:** For advanced prompt management and integration.
- And, of course, thanks to the community and contributors who helped shape this project.
---
Enjoy using the model and these examples as a reference for building your own prompt-driven applications! Happy coding! |