fullstack commited on
Commit
35311ae
1 Parent(s): 80e252f

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +191 -202
  2. gradio_gemma2-2b.py +97 -0
README.md CHANGED
@@ -1,202 +1,191 @@
1
- ---
2
- base_model: unsloth/gemma-2-2b
3
- library_name: peft
4
- ---
5
-
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
-
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
200
- ### Framework versions
201
-
202
- - PEFT 0.12.0
 
1
+ # Instruct Evolve Pipeline
2
+
3
+ ## Key Feature
4
+ The pipeline can be used recursively, feeding enhanced tasks and responses back into the model to generate increasingly complex iterations.
5
+
6
+ Gemma2 2b base model is used for this pipeline at 10,000 context.
7
+
8
+ example VLLM run script located in repo as [run_gemma2-2b.sh](./run_gemma2-2b.sh)
9
+
10
+ example gradio script located in repo as [gradio_gemma2-2b.py](./gradio_gemma2-2b.py)
11
+
12
+
13
+ ## Overview
14
+ Instruct Evolve is a pipeline that generates increasingly complex tasks and responses for a given Title and Context, using a base model fine-tuned on a specific prompt pipeline.
15
+
16
+ ## Process Flow
17
+ 1. Input: Title and Context
18
+ 2. Output: Task, Response, Enhanced Task, Enhanced Response
19
+
20
+
21
+ ## Usage
22
+ Zero-shot the base model with pseudo XML, or start with an existing type, task, and response, and enhance it further.
23
+
24
+ Input:
25
+ ```xml
26
+ <title>Your Title</title>
27
+ <content>
28
+ Your multi-line content
29
+ </content>
30
+ ```
31
+
32
+ Output:
33
+ ```xml
34
+ <type>explanation</type>
35
+ <thinking>Thoughts on task type</thinking>
36
+ <task>Context-aware task</task>
37
+ <thinking>Thoughts on task response</thinking>
38
+ <response>Response to the task</response>
39
+ <thinking>Thoughts on enhancing the task</thinking>
40
+ <enhancedtask>More complex version of the task</enhancedtask>
41
+ <thinking>Thoughts on enhanced task response</thinking>
42
+ <response>Response to the enhanced task</response>
43
+ ```
44
+
45
+ ## Supported Task Types
46
+ - Question
47
+ - Explanation
48
+ - Analysis
49
+ - Comparison
50
+ - Application
51
+
52
+ ## Dataset Curation Process
53
+ 1. Generate 20k unique subject-context pairs
54
+ 2. Generate tasks for each pair
55
+ 3. Generate responses for each task
56
+ 4. Enhance tasks based on previous responses
57
+ 5. Generate responses for enhanced tasks
58
+ 6. Repeat enhancement process 3 times
59
+ 7. Generate 5500 samples using Gemma2 9b instruct
60
+ 8. Clean and format data
61
+ 9. Create final dataset
62
+ 10. Train model using unsloth/Qwen2.5-3B with specific parameters
63
+
64
+
65
+ ### Input
66
+
67
+ ```xml
68
+ <title>Fission Products</title>
69
+ <content>
70
+ **Category: Thouless Pumping in Nuclear Physics**
71
+ **Document:**
72
+ Consider the Thouless pumping effect in a nuclear reactor. This effect is attributed to the presence of a high-energy neutron stream that can interact with a large number of fertile nuclei, inducing fission reactions.
73
+ **Question:**
74
+ A nuclear reactor is operating at a criticality level. A high-energy neutron stream passes through the reactor, initiating a large number of fission events.
75
+ The neutron stream is depleted due to the absorption of neutrons by the fission products.
76
+ Explain how the neutron stream's density and flux are affected by the Thouless pumping mechanism and the subsequent decay of fission products.
77
+ **Answer:**
78
+ The Thouless pumping effect amplifies the neutron stream's density and flux in a nuclear reactor.
79
+ The high-energy neutron stream induces a cascade of fission reactions, which produce a large number of fission products. These fission products absorb neutrons, resulting in a significant decrease in the neutron density and flux.
80
+ However, the fission products themselves undergo radioactive decay, releasing energetic particles and gamma rays. These decays continue to replenish the neutron stream, effectively negating the initial depletion.
81
+ **Reasoning Steps:**
82
+ 1. **Understand the concept of Thouless pumping:** Thouless pumping is a perturbation effect in neutron physics where a strong neutron flow causes a cascade of fission reactions, leading to an increase in neutron density and flux.
83
+ 2. **Analyze the interaction between neutrons and fission products:** When neutrons interact with fission products, they are absorbed by the fission products. This absorption leads to a decrease in the neutron density and flux.
84
+ 3. **Recognize the role of radioactive decay:** Radioactive decay of fission products releases energetic particles and gamma rays. These decays replenish the neutron stream, negating the initial depletion.
85
+ 4. **Consider the long-term impact:** The ongoing decay of fission products maintains a relatively constant neutron density and flux, ensuring the reactor's criticality is maintained.
86
+ **Key Concepts:**
87
+ * Thouless pumping
88
+ * Neutron Physics
89
+ * Nuclear Fission
90
+ * Neutron Density
91
+ * Neutron Flux
92
+ * Radioactive Decay
93
+ * Fission Products
94
+ * Criticality
95
+ The Thouless pumping mechanism plays a crucial role in enhancing the neutron stream's density and flux in a nuclear reactor. This mechanism is triggered by a high-energy neutron stream, which induces a cascade of fission reactions. As a result, the number of fission products rapidly increases, leading to a significant generation of radioactive isotopes.
96
+ These fission products are highly neutron-absorbing, and as they accumulate in the reactor, they absorb a substantial amount of neutrons. This absorption causes a sharp decrease in the neutron density and flux within the reactor.
97
+ However, the decay of these fission products is a critical factor that helps to maintain and even augment the neutron stream. The high-energy fission products decay through various modes, releasing energetic particles such as alpha and beta particles, as well as gamma rays. These decays introduce a continuous supply of neutrons into the reactor system through neutron emission, scintillation of the emitted particles, and other nuclear reactions.
98
+ In summary, the Thouless pumping mechanism amplifies the neutron stream's density and flux by initiating a cascade of fission reactions. The subsequent decay of fission products releases new neutrons into the reactor, thus counteracting the initial depletion. This process ensures that the neutron density and flux are sustained over the long term. $ \boxed{16} $
99
+ Reasoning: Let's think step by step in order to understand the effect of Thouless pumping and the decay of fission products on neutron stream density and flux.
100
+ Explanation:
101
+ The Thouless pumping mechanism is a phenomenon where a strong input of high-energy neutrons into a reactor leads to a sustained, amplified neutron flux. Here’s a step-by-step breakdown of how this affects neutron stream density and flux, especially considering the decay of fission products:
102
+ 1. **Thouless Pumping Mechanism:**
103
+ - **Input of High-Energy Neutrons:** The initial high-energy neutron stream, typically from external sources or fission reactions, is directly fed into the reactor.
104
+ - **Fission Reactions:** These high-energy neutrons induce fission reactions in heavy nuclei, producing a chain of fission events.
105
+ - **Fission Products:** As a result, a large number of fission products are created, which are highly neutron-absorbing isotopes.
106
+ - **Neutron Densification:** The generation of many fission products leads to an increase in neutron density inside the reactor.
107
+ 2. **Neutron Stream Density and Flux:**
108
+ - **Density Increase:** The presence of numerous fission products increases the overall neutron density in the reactor.
109
+ - **Flux Increase:** The continuous fission reactions create a high rate of neutron production, leading to a higher neutron flux.
110
+ - **Pumping Effect:** The accumulated fission products maintain a positive feedback loop, as their presence ensures a continuous influx of neutrons, further increasing the neutron density and flux.
111
+ 3. **Decay of Fission Products:**
112
+ - **Neutron Release:** When the fission products decay, they release additional neutrons. This is because the decay processes themselves produce additional energetic particles and γ-rays.
113
+ - **Neutron Emission:** These decaying fission products can undergo various decay modes that release neutrons, such as alpha decay, beta decay, and γ-decay.
114
+ - **Replenishment of Ne The Thouless pumping mechanism plays a crucial role in enhancing the neutron stream's density and flux in a nuclear reactor. This mechanism is triggered by a high-energy neutron stream, which induces a cascade of fission reactions. As a result, the number of fission products rapidly increases, leading to a significant generation of radioactive isotopes.
115
+ These fission products are highly neutron-absorbing, and as they accumulate in the reactor, they absorb a substantial amount of neutrons. This absorption causes a sharp decrease in the neutron density and flux within the reactor.
116
+ However, the decay of these fission products is a critical factor that helps to maintain and even augment the neutron stream. The high-energy fission products decay through various modes, releasing energetic particles such as alpha and beta particles, as well as gamma rays. These decays introduce a continuous supply of neutrons into the reactor system through neutron emission, scintillation of the emitted particles, and other nuclear reactions.
117
+ In summary, the Thouless pumping mechanism amplifies the neutron stream's density and flux by initiating a cascade of fission reactions. The subsequent decay of fission products releases new neutrons into the reactor, thus counteracting the initial depletion. This process ensures that the neutron density and flux are sustained over the long term. $ \boxed{16} $
118
+ Reasoning: Let's think step by step in order to understand the effect of Thouless pumping and the decay of fission products on neutron stream density and flux.
119
+ Explanation:
120
+ The Thouless pumping mechanism is a phenomenon where a strong input of high-energy neutrons into a reactor leads to a sustained, amplified neutron flux. Here’s a step-by-step breakdown of how this affects neutron stream density and flux, especially considering the decay of fission products:
121
+ 1. **Thouless Pumping Mechanism:**
122
+ - **Input of High-Energy Neutrons:** The initial high-energy neutron stream, typically from external sources or fission reactions, is directly fed into the reactor.
123
+ - **Fission Reactions:** These high-energy neutrons induce fission reactions in heavy nuclei, producing a chain of fission events.
124
+ - **Fission Products:** As a result, a large number of fission products are created, which are highly neutron-absorbing isotopes.
125
+ - **Neutron Densification:** The generation of many fission products leads to an increase in neutron density inside the reactor.
126
+ 2. **Neutron Stream Density and Flux:**
127
+ - **Density Increase:** The presence of numerous fission products increases the overall neutron density in the reactor.
128
+ - **Flux Increase:** The continuous fission reactions create a high rate of neutron production, leading to a higher neutron flux.
129
+ - **Pumping Effect:** The accumulated fission products maintain a positive feedback loop, as their presence ensures a continuous influx of neutrons, further increasing the neutron density and flux.
130
+ 3. **Decay of Fission Products:**
131
+ - **Neutron Release:** When the fission products decay, they release additional neutrons. This is because the decay processes themselves produce additional energetic particles and γ-rays.
132
+ - **Neutron Emission:** These decaying fission products can undergo various decay modes that release neutrons, such as alpha decay, beta decay, and γ-decay.
133
+ - **Replenishment of Ne
134
+ </content>
135
+ ```
136
+
137
+ ### Output
138
+
139
+ ```xml
140
+ <type>explanation</type>
141
+ <thinking> To compare the effects of Thouless pumping and the decay of fission products on neutron stream density and flux, we need to analyze their individual contributions and how they interact. </thinking>
142
+ <task> Compare and contrast the effects of the Thouless pumping mechanism and the decay of fission products on the density and flux of neutrons within a nuclear reactor. Discuss how these two phenomena work together to maintain a sustained neutron stream. </task>
143
+ <thinking>
144
+ Both the Thouless pumping mechanism and the decay of fission products contribute to maintaining a sustained neutron stream in a nuclear reactor, but they do so through distinct processes.
145
+ Thouless pumping amplifies the neutron flux by creating a positive feedback loop. The initial high-energy neutron stream triggers a cascade of fission reactions, producing more neutrons. These newly produced neutrons further induce fission, leading to a rapid increase in neutron density and flux.
146
+ Fission product decay, on the other hand, replenishes the neutron stream by releasing neutrons during the radioactive decay process. While fission products absorb neutrons, their decay releases a continuous supply of neutrons back into the reactor core, counteracting the absorption and ensuring a sustained neutron population.
147
+ </thinking>
148
+ <response>
149
+ The Thouless pumping mechanism and the decay of fission products are two crucial factors that work together to maintain a sustained neutron stream in a nuclear reactor.
150
+ **Thouless Pumping:**
151
+ * **Mechanism:** A high-energy neutron stream triggers a cascade of fission reactions, leading to a rapid increase in neutron density and flux.
152
+ * **Effect:** Amplifies the neutron stream by creating a positive feedback loop.
153
+ * **Key Feature:** Driven by the initial input of high-energy neutrons and the chain reaction of fission.
154
+ **Decay of Fission Products:**
155
+ * **Mechanism:** Radioactive decay of fission products releases neutrons as part of the decay process.
156
+ * **Effect:** Replenishes the neutron stream, counteracting the absorption by fission products.
157
+ * **Key Feature:** A continuous process that provides a steady supply of neutrons over time.
158
+ **Working Together:**
159
+ Thouless pumping initially creates a surge in neutron density and flux, while the decay of fission products provides a continuous source of neutrons to sustain the chain reaction. This interplay ensures that the reactor core maintains a critical state, with a sufficient neutron population to sustain fission reactions and generate power.
160
+ **In essence:** Thouless pumping provides the initial boost, and fission product decay acts as the sustainer, keeping the neutron stream flowing and the reactor operating.
161
+ </response>
162
+ <thinking>
163
+ The previous response provides a good basic understanding of Thouless pumping and fission product decay. However, it could be enhanced by:
164
+ * **Deeper Dive into Decay Modes:** Elaborating on the specific decay modes (alpha, beta, gamma) and how they contribute to neutron release would add depth.
165
+ * **Neutron Absorption Cross-Sections:** Mentioning the concept of neutron absorption cross-sections for different fission products would highlight the varying degrees of neutron absorption.
166
+ * **Reactor Control:** Discussing how reactor control mechanisms (e.g., control rods) are used to manage the neutron population in relation to Thouless pumping and fission product decay would provide a more complete picture.
167
+ </thinking>
168
+ <enhancedtask> Investigate the specific roles of alpha, beta, and gamma decay in releasing neutrons from fission products. How do the neutron absorption cross-sections of different fission products influence the overall neutron density and flux in a reactor? Explain how reactor control mechanisms, such as control rods, are used to manage the neutron population in the context of Thouless pumping and fission product decay. </enhancedtask>
169
+ <thinking>
170
+ Here's a breakdown of the roles of alpha, beta, and gamma decay in neutron release, the impact of fission product cross-sections, and how control rods manage neutron populations in a reactor:
171
+ **Alpha, Beta, and Gamma Decay and Neutron Release:**
172
+ * **Alpha Decay:** Alpha particles are essentially helium nuclei (two protons and two neutrons). While alpha decay releases energy, it doesn't directly produce neutrons.
173
+ * **Beta Decay:** Beta decay involves the transformation of a neutron into a proton (beta-minus decay) or a proton into a neutron (beta-plus decay).
174
+ * **Beta-minus decay:** A neutron decays into a proton, emitting an electron (beta particle) and an antineutrino. This process can sometimes result in the emission of a neutron.
175
+ * **Beta-plus decay:** A proton decays into a neutron, emitting a positron (antielectron) and a neutrino. This process does not directly produce neutrons.
176
+ * **Gamma Decay:** Gamma decay involves the release of high-energy photons (gamma rays) from an excited nucleus. While gamma rays can interact with matter and potentially induce fission, they don't directly produce neutrons.
177
+ **Neutron Absorption Cross-Sections:**
178
+ * **Cross-Section:** The neutron absorption cross-section of a nucleus is a measure of its probability of absorbing a neutron.
179
+ * **Fission Product Variation:** Different fission products have vastly different neutron absorption cross-sections. Some are highly neutron-absorbing (e.g., xenon isotopes), while others are less so.
180
+ * **Impact on Neutron Density and Flux:** The abundance and neutron absorption cross-sections of fission products directly influence the neutron density and flux in a reactor. High neutron absorption by fission products can lead to a decrease in neutron population, potentially causing the reactor to become subcritical.
181
+ **Reactor Control Mechanisms (Control Rods):**
182
+ * **Purpose:** Control rods are made of materials with very high neutron absorption cross-sections (e.g., boron, cadmium). They are inserted into the reactor core to absorb excess neutrons and regulate the chain reaction.
183
+ * **Thouless Pumping and Control:** In the context of Thouless pumping, control rods are crucial for managing the amplified neutron flux. They prevent the reactor from becoming supercritical and potentially leading to a runaway chain reaction.
184
+ * **Operation:** By adjusting the position of control rods, operators can fine-tune the neutron population in the reactor. Inserting rods further into the core increases neutron absorption, slowing down the chain reaction. Withdrawing rods allows more neutrons to participate in fission, increasing the reactor power.
185
+ </thinking>
186
+ <response>
187
+ The decay of fission products plays a crucial role in the neutron population dynamics of a nuclear reactor, particularly in the context of Thouless pumping. While alpha decay does not directly release neutrons, beta decay can sometimes result in neutron emission. Gamma decay, while not directly producing neutrons, can contribute to neutron production through interactions with matter.
188
+ The neutron absorption cross-sections of different fission products significantly influence the overall neutron density and flux. Highly neutron-absorbing fission products, such as xenon isotopes, can lead to a decrease in neutron population, potentially causing the reactor to become subcritical.
189
+ Reactor control mechanisms, such as control rods, are essential for managing the neutron population in the context of Thouless pumping and fission product decay. Control rods, made of materials with high neutron absorption cross-sections, are inserted into the reactor core to absorb excess neutrons and regulate the chain reaction. By adjusting the position of control rods, operators can fine-tune the neutron population, preventing the reactor from becoming supercritical and ensuring safe and controlled operation.
190
+ </response>
191
+ ```
 
 
 
 
 
 
 
 
 
 
 
gradio_gemma2-2b.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import re
4
+ import html
5
+ import traceback
6
+ import logging
7
+
8
+ # Set up logging
9
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
+
11
+ VLLM_URL = "http://localhost:6002/v1/completions"
12
+ MODEL = "lora"
13
+
14
+ def flexible_parse(text):
15
+ pattern = r'<(\w+)(?:\s+[^>]*)?>((?:(?!<\1).)*?)</\1>|<(\w+)(?:\s+[^>]*)?>'
16
+ result = []
17
+
18
+ for match in re.finditer(pattern, text):
19
+ tag, content, single_tag = match.groups()
20
+ if single_tag:
21
+ result.append((single_tag, ''))
22
+ elif tag:
23
+ result.append((tag, content.strip() if content else ''))
24
+
25
+ return result
26
+
27
+ def format_as_collapsible_markdown(parsed_content):
28
+ markdown = ""
29
+ for tag, content in parsed_content:
30
+ if content:
31
+ markdown += f'<details>\n<summary><strong>{html.escape(tag)}</strong></summary>\n\n{html.escape(content)}\n\n</details>\n\n'
32
+ else:
33
+ markdown += f'<strong>{html.escape(tag)}</strong>\n\n'
34
+ return markdown
35
+
36
+ def get_completion(title: str, prompt: str):
37
+ full_prompt = f"<title>{title}</title>\n<content>\n{prompt}\n</content>"
38
+ try:
39
+ logging.info(f"Sending request to VLLM server: {VLLM_URL}")
40
+ response = requests.post(
41
+ VLLM_URL,
42
+ json={
43
+ "prompt": full_prompt,
44
+ "max_tokens": 6000,
45
+ "temperature": 1,
46
+ "model": MODEL
47
+ },
48
+ timeout=30000 # Add a timeout
49
+ )
50
+ response.raise_for_status() # Raise an exception for bad status codes
51
+ logging.info("Successfully received response from VLLM server")
52
+ return response.json()["choices"][0]["text"]
53
+ except requests.exceptions.RequestException as e:
54
+ logging.error(f"Error connecting to VLLM server: {str(e)}")
55
+ return f"Error connecting to VLLM server: {str(e)}"
56
+ except Exception as e:
57
+ logging.error(f"Unexpected error in get_completion: {str(e)}")
58
+ return f"Unexpected error: {str(e)}\n{traceback.format_exc()}"
59
+
60
+ def gradio_interface(title, prompt):
61
+ try:
62
+ logging.info(f"Received request - Title: {title}, Prompt: {prompt}")
63
+ raw_response = get_completion(title, prompt)
64
+ parsed_content = flexible_parse(raw_response)
65
+ collapsible_view = format_as_collapsible_markdown(parsed_content)
66
+
67
+ combined_output = f"""
68
+ ## Raw Response:
69
+
70
+ ```
71
+ {raw_response}
72
+ ```
73
+
74
+ ## Parsed Structure:
75
+
76
+ {collapsible_view}
77
+ """
78
+ logging.info("Successfully processed request")
79
+ return combined_output
80
+ except Exception as e:
81
+ logging.error(f"Error in gradio_interface: {str(e)}")
82
+ return f"Error in gradio_interface: {str(e)}\n{traceback.format_exc()}"
83
+
84
+ iface = gr.Interface(
85
+ fn=gradio_interface,
86
+ inputs=[
87
+ gr.Textbox(label="Title"),
88
+ gr.Textbox(label="Prompt", lines=5)
89
+ ],
90
+ outputs=gr.Markdown(label="Response and Parsed Structure"),
91
+ title="VLLM Completion Client with Raw Response and Collapsible View",
92
+ description=f"Enter a title and prompt to generate a completion using the {MODEL} model. The raw response and a collapsible view of the parsed structure will be displayed."
93
+ )
94
+
95
+ if __name__ == "__main__":
96
+ logging.info("Starting Gradio interface")
97
+ iface.launch()