Skip to content

Commit 9736016

Browse files
committed
choose()
1 parent 71cadf9 commit 9736016

File tree

4 files changed

+260
-99
lines changed

4 files changed

+260
-99
lines changed

README.md

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ generate("Describe the water cycle.", quantize_model=True)
6666
generate("Explain quantum computing.", quantize_cache=True)
6767
```
6868

69-
### Structured Generation Using Constrained Decoding (WIP)
69+
### Constrained Decoding (WIP)
7070

7171
The `constrain` function allows for structured generation, which can be useful for tasks like code generation, function calling, chain-of-thought prompting, or multiple-choice question answering.
7272

@@ -104,12 +104,36 @@ The most likely cause of this patient's menorrhagia and easy bruising is E: Von
104104
105105
< Generated text for prompt #1 >
106106
The patient's hypertension, edema, and weight gain are concerning for preeclampsia. The correct answer is E: 24-hour urine protein.
107-
(phi) phi %
107+
```
108+
109+
### Multiple Choice Selection
110+
111+
The `choose` function provides a straightforward way to select the best option from a set of choices for a given prompt. This is particularly useful for multiple-choice questions or decision-making scenarios.
112+
113+
```python
114+
from phi_3_vision_mlx import choose
115+
116+
prompt = "What is the capital of France? A: London B: Berlin C: Paris D: Madrid E: Rome"
117+
result = choose(prompt)
118+
print(result) # Output: 'C'
119+
120+
# Using with custom choices
121+
custom_prompt = "Which color is associated with stopping at traffic lights? R: Red Y: Yellow G: Green"
122+
custom_result = choose(custom_prompt, choices='RYG')
123+
print(custom_result) # Output: 'R'
124+
125+
# Batch processing
126+
prompts = [
127+
"What is the largest planet in our solar system? A: Earth B: Mars C: Jupiter D: Saturn",
128+
"Which element has the chemical symbol 'O'? A: Osmium B: Oxygen C: Gold D: Silver"
129+
]
130+
batch_results = choose(prompts)
131+
print(batch_results) # Output: ['C', 'B']
108132
```
109133

110134
### (Q)LoRA Fine-tuning
111135

112-
Training a (Q)LoRA Adapter
136+
Training a LoRA Adapter
113137

114138
```python
115139
from phi_3_vision_mlx import train_lora
@@ -126,7 +150,7 @@ train_lora(
126150

127151
![Alt text](https://raw.githubusercontent.com/JosefAlbers/Phi-3-Vision-MLX/main/assets/train_log.png)
128152

129-
Generating Text with (Q)LoRA
153+
Generating Text with LoRA
130154

131155
```python
132156
generate("Describe the potential applications of CRISPR gene editing in medicine.",
@@ -135,7 +159,7 @@ generate("Describe the potential applications of CRISPR gene editing in medicine
135159
use_adapter=True)
136160
```
137161

138-
Comparing (Q)LoRA Adapters
162+
Comparing LoRA Adapters
139163

140164
```python
141165
from phi_3_vision_mlx import test_lora
@@ -206,12 +230,7 @@ agent.end()
206230
### Example 1. In-Context Learning Agent
207231

208232
```python
209-
from phi_3_vision_mlx import _load_text
210-
211-
# Create a custom tool named 'add_text'
212-
def add_text(prompt):
213-
prompt, path = prompt.split('@')
214-
return f'{_load_text(path)}\n<|end|>\n<|user|>{prompt}'
233+
from phi_3_vision_mlx import add_text
215234

216235
# Define the toolchain as a string
217236
toolchain = """
@@ -240,7 +259,7 @@ def rag(prompt, repo_id="JosefAlbers/sharegpt_python_mlx", n_topk=1):
240259
ds = datasets.load_dataset(repo_id, split='train')
241260
vdb = VDB(ds)
242261
context = vdb(prompt, n_topk)[0][0]
243-
return f'{context}\n<|end|>\n<|user|>Plot: {prompt}'
262+
return f'{context}\n<|end|>\n<|user|>\nPlot: {prompt}'
244263

245264
# Define the toolchain
246265
toolchain_plot = """
Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,36 @@
1-
# This file was authored by GitHub user @couillonnade (PR #2)
1+
# This file was originally authored by GitHub user @couillonnade (PR #2)
22

3-
import sys
4-
from pathlib import Path
5-
sys.path.append(str(Path(__file__).parent))
3+
import phi_3_vision_mlx as pv
64

7-
from phi_3_vision_mlx import Agent
5+
# Decoding Strategies
6+
7+
## Multiple Choice Question Answering 1
8+
prompts = [
9+
"A 20-year-old woman presents with menorrhagia for the past several years. She says that her menses “have always been heavy”, and she has experienced easy bruising for as long as she can remember. Family history is significant for her mother, who had similar problems with bruising easily. The patient's vital signs include: heart rate 98/min, respiratory rate 14/min, temperature 36.1°C (96.9°F), and blood pressure 110/87 mm Hg. Physical examination is unremarkable. Laboratory tests show the following: platelet count 200,000/mm3, PT 12 seconds, and PTT 43 seconds. Which of the following is the most likely cause of this patient’s symptoms? A: Factor V Leiden B: Hemophilia A C: Lupus anticoagulant D: Protein C deficiency E: Von Willebrand disease",
10+
"A 25-year-old primigravida presents to her physician for a routine prenatal visit. She is at 34 weeks gestation, as confirmed by an ultrasound examination. She has no complaints, but notes that the new shoes she bought 2 weeks ago do not fit anymore. The course of her pregnancy has been uneventful and she has been compliant with the recommended prenatal care. Her medical history is unremarkable. She has a 15-pound weight gain since the last visit 3 weeks ago. Her vital signs are as follows: blood pressure, 148/90 mm Hg; heart rate, 88/min; respiratory rate, 16/min; and temperature, 36.6℃ (97.9℉). The blood pressure on repeat assessment 4 hours later is 151/90 mm Hg. The fetal heart rate is 151/min. The physical examination is significant for 2+ pitting edema of the lower extremity. Which of the following tests o should confirm the probable condition of this patient? A: Bilirubin assessment B: Coagulation studies C: Hematocrit assessment D: Leukocyte count with differential E: 24-hour urine protein"]
11+
pv.choose("What is the capital of France? A: London B: Berlin C: Paris D: Madrid E: Rome")
12+
13+
## Multiple Choice Question Answering 2
14+
pv.constrain(prompts, constraints=[(30, ' The correct answer is'), (10, 'X.')], blind_model=True, quantize_model=True)
15+
16+
## Code Generation
17+
pv.constrain("Write a Python function to calculate the Fibonacci sequence up to a given number n.", [(100, "\n```python\n"), (100, " return "), (200, "\n```")])
18+
19+
# Train
20+
pv.train_lora(
21+
lora_layers=5, # Number of layers to apply LoRA
22+
lora_rank=16, # Rank of the LoRA adaptation
23+
epochs=10, # Number of training epochs
24+
lr=1e-4, # Learning rate
25+
warmup=0.5, # Fraction of steps for learning rate warmup
26+
dataset_path="JosefAlbers/akemiH_MedQA_Reason"
27+
)
28+
29+
# Test
30+
pv.test_lora()
831

932
# Multi-turn VQA
10-
agent = Agent()
33+
agent = pv.Agent()
1134
agent('What is shown in this image?', 'https://collectionapi.metmuseum.org/api/collection/v1/iiif/344291/725918/main-image')
1235
agent('What is the location?')
1336
agent.end()
@@ -23,26 +46,9 @@
2346
agent('Speak "People say nothing is impossible, but I do nothing every day."')
2447
agent.end()
2548

26-
from phi_3_vision_mlx import constrain
27-
28-
# Code Generation
29-
constrain ("Write a Python function to calculate the Fibonacci sequence up to a given number n.", [(100, "\n```python\n"), (100, " return "), (200, "\n```")])
30-
31-
# Multiple Choice Question Answering
32-
prompts = [
33-
"A 20-year-old woman presents with menorrhagia for the past several years. She says that her menses “have always been heavy”, and she has experienced easy bruising for as long as she can remember. Family history is significant for her mother, who had similar problems with bruising easily. The patient's vital signs include: heart rate 98/min, respiratory rate 14/min, temperature 36.1°C (96.9°F), and blood pressure 110/87 mm Hg. Physical examination is unremarkable. Laboratory tests show the following: platelet count 200,000/mm3, PT 12 seconds, and PTT 43 seconds. Which of the following is the most likely cause of this patient’s symptoms? A: Factor V Leiden B: Hemophilia A C: Lupus anticoagulant D: Protein C deficiency E: Von Willebrand disease",
34-
"A 25-year-old primigravida presents to her physician for a routine prenatal visit. She is at 34 weeks gestation, as confirmed by an ultrasound examination. She has no complaints, but notes that the new shoes she bought 2 weeks ago do not fit anymore. The course of her pregnancy has been uneventful and she has been compliant with the recommended prenatal care. Her medical history is unremarkable. She has a 15-pound weight gain since the last visit 3 weeks ago. Her vital signs are as follows: blood pressure, 148/90 mm Hg; heart rate, 88/min; respiratory rate, 16/min; and temperature, 36.6℃ (97.9℉). The blood pressure on repeat assessment 4 hours later is 151/90 mm Hg. The fetal heart rate is 151/min. The physical examination is significant for 2+ pitting edema of the lower extremity. Which of the following tests o should confirm the probable condition of this patient? A: Bilirubin assessment B: Coagulation studies C: Hematocrit assessment D: Leukocyte count with differential E: 24-hour urine protein"]
35-
constrain(prompts, constraints=[(30, ' The correct answer is'), (10, 'X.')], blind_model=True, quantize_model=True)
36-
37-
from phi_3_vision_mlx import train_lora, test_lora
38-
39-
# Train
40-
train_lora(lora_layers=5, lora_rank=16, epochs=10, take=10, batch_size=2, lr=1e-4, warmup=.5, dataset_path="JosefAlbers/akemiH_MedQA_Reason")
41-
42-
# Test
43-
test_lora()
44-
45-
from phi_3_vision_mlx import benchmark
49+
# Misc
50+
pv.add_text('How to inspect API endpoints? @https://raw.githubusercontent.com/gradio-app/gradio/main/guides/08_gradio-clients-and-lite/01_getting-started-with-the-python-client.md')
51+
pv.rag('Comparison of Sortino Ratio for Bitcoin and Ethereum.')
4652

4753
# Benchmark
48-
benchmark()
54+
pv.benchmark()

0 commit comments

Comments
 (0)