---
license: apache-2.0
language:
- en
base_model:
- >-
  MasterControlAIML/DeepSeek-R1-Strategy-Qwen-2.5-1.5b-Unstructured-To-Structured
pipeline_tag: text-generation 
library_name: transformers
tags:
- DeepSeek
- R1
- SFT
- Qwen
- JSON
- Unstructured
- Structured
---

# MasterControlAIML R1-Qwen2.5-1.5b SFT R1 JSON Unstructured-To-Structured Model

[![Unsloth](https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png)](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:** [bhaviktheslider](https://github.com/bhaviktheslider)
> - **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"

# 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"

# 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 the `<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!
```