Views
No views yet
Key Highlights:
- Developed by: bhaviktheslider
- License: Apache-2.0
- Finetuned from:
MasterControlAIML/DeepSeek-R1-Strategy-Qwen-2.5-1.5b-Unstructured-To-Structured- Accelerated Training: Achieved 2x faster training using Unsloth and Hugging Face's TRL library.
transformers, torch, unsloth, langchain (for advanced usage)pip install torch transformers unsloth langchain1from unsloth import FastLanguageModel
2import torch
3
4MODEL = "MasterControlAIML/DeepSeek-R1-Qwen2.5-1.5b-SFT-R1-JSON-Unstructured-To-Structured"
5
6# Load model and tokenizer
7model, tokenizer = FastLanguageModel.from_pretrained(
8 model_name=MODEL,
9 max_seq_length=2048,
10 dtype=None,
11 load_in_4bit=False,
12)
13
14# Prepare for inference
15FastLanguageModel.for_inference(model)
16
17ALPACA_PROMPT = """
18Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
19### Instruction:
20{}
21### Response:
22{}
23"""
24
25# Example instruction and prompt
26instruction = "" (see examples below)
27prompt = ALPACA_PROMPT.format(instruction, "")
28inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
29output = model.generate(**inputs, max_new_tokens=2000)
30
31# Print generated text
32print(tokenizer.batch_decode(output, skip_special_tokens=True)[0])1from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
2import torch
3
4MODEL = "MasterControlAIML/DeepSeek-R1-Qwen2.5-1.5b-SFT-R1-JSON-Unstructured-To-Structured"
5
6# Initialize tokenizer and model
7tokenizer = AutoTokenizer.from_pretrained(MODEL)
8model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.float16, device_map="auto")
9
10ALPACA_PROMPT = """
11Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
12### Instruction:
13{}
14### Response:
15{}
16"""
17
18TEXT = ""(see examples below)
19prompt = ALPACA_PROMPT.format(TEXT, "")
20inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
21text_streamer = TextStreamer(tokenizer)
22
23with torch.no_grad():
24 output_ids = model.generate(
25 input_ids=inputs["input_ids"],
26 attention_mask=inputs["attention_mask"],
27 max_new_tokens=2000,
28 temperature=0.7,
29 top_p=0.9,
30 repetition_penalty=1.1,
31 streamer=text_streamer,
32 pad_token_id=tokenizer.pad_token_id,
33 )
34
35print(tokenizer.decode(output_ids[0], skip_special_tokens=True))1from langchain_core.prompts import PromptTemplate
2
3# Sample text input with a slightly different structure
4TEXT1 = """
5Quality Assurance Manual Overview
6
7This document provides an introduction to the quality assurance procedures for manufacturing processes.
8
9## Introduction to Manufacturing Processes
10
11This section covers the basics of manufacturing processes. It includes definitions and a brief history.
12
13| Name | Description |
14|---------------------|---------------------------|
15| Process 1 | Initial process in制造过程。|
16
17### Detailed Process 1
18
19This process refines material to meet specific standards.
20
21| Parameter | Range |
22|-----------|----------|
23| Temperature | 200-300°C |
24
25**Operational Parameters**
26
27The operational parameters are critical for the success of this process.
28
29| Setting | Class |
30|---------|------------|
31| Critical | High Precision |
32"""
33
34# A different JSON schema example
35SCHEMA1 = """
36{
37 "$schema": "http://json-schema.org/draft-07/schema#",
38 "type": "object",
39 "properties": {
40 "id": {
41 "type": "string",
42 "description": "Dot-separated integers representing the hierarchical id of the element."
43 },
44 "title": {
45 "type": "string",
46 "description": "Descriptive title of the section or component."
47 },
48 "level": {
49 "type": "integer",
50 "description": "Hierarchy level starting from 0 for the root."
51 },
52 "level_type": {
53 "type": "string",
54 "enum": ["ROOT", "SECTION", "SUBSECTION", "DETAIL_N"],
55 "description": "Type of the hierarchal level."
56 },
57 "component": {
58 "type": "array",
59 "items": {
60 "type": "object",
61 "properties": {
62 "idc": {
63 "type": "integer",
64 "description": "Sequential unique component ID."
65 },
66 "component_type": {
67 "type": "string",
68 "enum": ["PARAGRAPH", "TABLE", "CALCULATION", "CHECKBOX"],
69 "description": "Type of the component."
70 },
71 "metadata": {
72 "type": "string",
73 "description": "Additional metadata token (may be <title>, <note>, or <overview>)."
74 },
75 "properties": {
76 "type": "object",
77 "properties": {
78 "variables": {
79 "type": "array",
80 "items": {
81 "type": "object",
82 "properties": {
83 "idx": {
84 "type": "string",
85 "description": "Unique identifier, X.Y (X represents row, Y represents column for Tables, 0 otherwise)."
86 },
87 "name": {
88 "type": "string",
89 "description": "Attribute name."
90 },
91 "value": {
92 "type": "string",
93 "description": "Attribute value."
94 },
95 "unit": {
96 "type": "string",
97 "description": "Optional unit."
98 },
99 "metrics": {
100 "type": "boolean",
101 "description": "Flag indicating if variable is a metric."
102 },
103 "formula": {
104 "type": "boolean",
105 "description": "Flag indicating if variable has an equation."
106 }
107 }
108 }
109 },
110 "content": {
111 "type": "array",
112 "items": {
113 "type": "string"
114 },
115 "description": "Text content (e.g., notes, MCQs, questions, points, etc.)."
116 }
117 }
118 }
119 }
120 }
121 },
122 "children": {
123 "type": "array",
124 "items": {
125 "$ref": "#"
126 },
127 "description": "Nested elements."
128 }
129 },
130 "required": ["id", "title", "level", "level_type", "component", "children"]
131}
132"""
133
134# LangChain prompt to guide the model
135SYSTEM_PROMPT = """
136### Role:
137You are an expert data extractor specializing in mapping hierarchical text data into a given JSON Schema.
138
139### DATA INPUT:
140- **Text:** ```{TEXT}```
141- **Blank JSON Schema:** ```{SCHEMA}```
142
143### TASK REQUIREMENT:
1441. Analyze the given text and map all relevant information strictly into the provided JSON Schema.
1452. Provide your output in **two mandatory sections**:
146 - **`<answer>`:** The filled JSON object
147 - **`<think>`:** Reasoning for the mapping decisions
148
149### OUTPUT STRUCTURE:
150
151`<think> /* Explanation of mapping logic */ </think>`
152`<answer> /* Completed JSON Object */ </answer>`
153
154
155
156### STRICT RULES FOR GENERATING OUTPUT:
1571. **Both Tags Required:**
158 - Always provide both the `<think>` and the `<answer>` sections.
159 - If reasoning is minimal, state: "Direct mapping from text to schema."
1602. **JSON Schema Mapping:**
161 - Strictly map the text data to the given JSON Schema without modification or omissions.
1623. **Hierarchy Preservation:**
163 - Maintain proper parent-child relationships and follow the schema's hierarchical structure.
1644. **Correct Mapping of Attributes:**
165 - Map key attributes, including `id`, `idc`, `idx`, `level_type`, and `component_type`.
1665. **JSON Format Compliance:**
167 - Escape quotes (`\"`), replace newlines with `\\n`, avoid trailing commas, and use double quotes exclusively.
1686. **Step-by-Step Reasoning:**
169 - Explain your reasoning within the `<think>` tag.
170
171### IMPORTANT:
172If either the `<think>` or `<answer>` tags is missing, the response will be considered incomplete.
173"""
174
175from langchain_core.prompts import PromptTemplate
176system_prompt_template = PromptTemplate(template=SYSTEM_PROMPT, input_variables=["TEXT", "SCHEMA"])
177
178# Format the prompt with your chosen text and JSON schema
179system_prompt_str = system_prompt_template.format(TEXT=TEXT1, SCHEMA=SCHEMA1)
180
181# Now, pass `system_prompt_str` into your model inference pipeline (using Unsloth, Transformers, etc.)
182# to get the output that contains both the reasoning and the mapped JSON object.<think>) and the corresponding Filled JSON Schema (<answer>). These examples show how the model should articulate its reasoning and produce the final mapped schema.1<think>
2Chain of Thought Explanation:
3To 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.
4
5First, 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.
6
7I 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.
8
9For 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.
10
11Next, 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.
12
13Then 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.
14
15Throughout 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.
16</think>
17
18<answer>{
19 "id": "0.0",
20 "title": "Quality Assurance Manual for Manufacturing Process",
21 "level": 0,
22 "level_type": "ROOT",
23 "component": [
24 {
25 "idc": 0,
26 "component_type": "PARAGRAPH",
27 "metadata": "<overview>This manual covers the QA procedures and guidelines for various manufacturing processes.</overview>",
28 "properties": {
29 "variables": [],
30 "content": []
31 }
32 }
33 ],
34 "children": [
35 {
36 "id": "1.0",
37 "title": "Introduction to Quality Assurance",
38 "level": 1,
39 "level_type": "SECTION",
40 "component": [
41 {
42 "idc": 0,
43 "component_type": "PARAGRAPH",
44 "metadata": "",
45 "properties": {
46 "variables": [],
47 "content": [
48 "Quality Assurance (QA) involves systematic activities designed to ensure consistent production of reliable and safe products.",
49 "It aims to reduce variability in the final product and improve overall efficiency."
50 ]
51 }
52 },
53 {
54 "idc": 1,
55 "component_type": "TABLE",
56 "metadata": "",
57 "properties": {
58 "variables": [
59 {
60 "idx": "0.0",
61 "name": "Metric",
62 "value": "Defect Rate",
63 "unit": "%",
64 "metrics": true,
65 "formula": false
66 },
67 {
68 "idx": "0.1",
69 "name": "Target",
70 "value": 0.5,
71 "unit": null,
72 "metrics": true,
73 "formula": false
74 }
75 ],
76 "content": []
77 }
78 }
79 ],
80 "children": [
81 {
82 "id": "1.1",
83 "title": "QA in Manufacturing Processes",
84 "level": 2,
85 "level_type": "SUBSECTION",
86 "component": [
87 {
88 "idc": 0,
89 "component_type": "PARAGRAPH",
90 "metadata": "",
91 "properties": {
92 "variables": [],
93 "content": [
94 "Manufacturing processes require strict adherence to QA procedures to ensure product reliability and safety."
95 ]
96 }
97 },
98 {
99 "idc": 1,
100 "component_type": "CHECKBOX",
101 "metadata": "",
102 "properties": {
103 "variables": [
104 {
105 "idx": "0.0",
106 "name": "Process Control",
107 "value": true,
108 "unit": null,
109 "metrics": false,
110 "formula": false
111 },
112 {
113 "idx": "0.1",
114 "name": "Raw Material Inspection",
115 "value": false,
116 "unit": null,
117 "metrics": false,
118 "formula": false
119 }
120 ],
121 "content": [
122 "Check if the following QA procedures are followed:",
123 "\u2713 Process Control \u2713 Raw Material Inspection"
124 ]
125 }
126 }
127 ],
128 "children": [
129 {
130 "id": "1.1.1",
131 "title": "Standard QA Practices",
132 "level": 3,
133 "level_type": "DETAIL_N",
134 "component": [
135 {
136 "idc": 0,
137 "component_type": "PARAGRAPH",
138 "metadata": "",
139 "properties": {
140 "variables": [],
141 "content": [
142 "Adherence to ISO 9001 standards helps maintain quality control."
143 ]
144 }
145 },
146 {
147 "idc": 1,
148 "component_type": "TABLE",
149 "metadata": "",
150 "properties": {
151 "variables": [
152 {
153 "idx": "0.0",
154 "name": "Comparison",
155 "value": "ISO 9001 vs ASQ-Certified QM",
156 "unit": null,
157 "metrics": false,
158 "formula": false
159 }
160 ],
161 "content": []
162 }
163 }
164 ],
165 "children": []
166 }
167 ]
168 }
169 ]
170 }
171 ]
172}</answer>1<think>
2Chain of Thought Explanation:
3
4To 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:
5
61. **Identify Components**: Recognize that both schemas contain similar structures with varying component types (Table, Paragraph, Checkbox).
7
82. **Extract Data from Text**:
9 - Locate tables containing variables like Defect Rate and Yield Rate in the introduction section.
10 - Identify confirmatory statements regarding defect identification and regular audits in sub-sections.
11
123. **Populate Variables**: Fill the Table component under "Key Metrics" with extracted variable names and values (Defect Rate=0.5%, Yield Rate=98%).
13
144. **Fill Checkboxes**: Convert bullet points into boolean values for checkboxes; set Confirmations to reflect findings (true for defects found, false for audits missed).
15
165. **Add Standards Table**: Create a second Table in the Details section comparing ISO 9001 and ASQ-Certified QM, mirroring the original.
17
18By 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.
19
20**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.
21</think>
22
23<answer>{
24 "id": "0.0",
25 "title": "Quality Assurance Manual",
26 "level": 0,
27 "level_type": "ROOT",
28 "component": [
29 {
30 "idc": 0
31 },
32 {
33 "idc": 1
34 }
35 ],
36 "children": [
37 {
38 "id": "1.0",
39 "title": "Introduction to Manufacturing Processes",
40 "level": 1,
41 "level_type": "SECTION",
42 "component": [],
43 "children": [
44 {
45 "id": "1.1",
46 "title": "Detailed Process 1",
47 "level": 2,
48 "level_type": "SUBSECTION",
49 "component": [],
50 "children": []
51 },
52 {
53 "id": "1.2",
54 "title": "Operational Details",
55 "level": 2,
56 "level_type": "SUBSECTION",
57 "component": [
58 {
59 "idc": 0,
60 "component_type": "PARAGRAPH",
61 "metadata": "<overview>This section outlines the operational aspects of Process 1.</overview>",
62 "properties": {}
63 }
64 ],
65 "children": []
66 }
67 ]
68 },
69 {
70 "id": "2.0",
71 "title": "Advanced Manufacturing Techniques",
72 "level": 1,
73 "level_type": "SECTION",
74 "component": [],
75 "children": [
76 {
77 "id": "2.1",
78 "title": "High-Temperature Processing",
79 "level": 2,
80 "level_type": "SUBSECTION",
81 "component": [
82 {
83 "idc": 0,
84 "component_type": "TABLE",
85 "metadata": "<title>Table of Specifications</title>",
86 "properties": {
87 "variables": [
88 {
89 "idx": "0.0",
90 "name": "Parameter",
91 "value": "Temperature",
92 "unit": "\u00b0C",
93 "metrics": true,
94 "formula": false
95 },
96 {
97 "idx": "1.0",
98 "name": "Range",
99 "value": "[200, 300]",
100 "unit": null,
101 "metrics": false,
102 "formula": false
103 }
104 ],
105 "content": [
106 "Note: Ensure temperature control within specified range."
107 ]
108 }
109 }
110 ],
111 "children": []
112 }
113 ]
114 }
115 ]
116}</answer>