Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

enhancement(documentation): adding initial docs for dspy LM, RM, teleprompting, local models and generic modules. (#123)

Sri Vardhamanan316f86c26771
diff --git a/docs/language_models_client.md b/docs/language_models_client.md
new file mode 100644
index 000000000..05e784a77
--- /dev/null
+++ b/docs/language_models_client.md
@@ -0,0 +1,158 @@
+# LM Modules Documentation
+
+This documentation provides an overview of the DSPy Language Model Clients.
+
+### Quickstart
+
+```python
+import dspy
+
+lm = dspy.OpenAI(model='gpt-3.5-turbo')
+
+prompt = "Translate the following English text to Spanish: 'Hi, how are you?'"
+completions = lm(prompt, n=5, return_sorted=False)
+for i, completion in enumerate(completions):
+ print(f"Completion {i+1}: {completion}")
+```
+
+## Supported LM Clients
+
+| LM Client | Jump To |
+| --- | --- |
+| OpenAI | [OpenAI Section](#openai) |
+| Cohere | [Cohere Section](#cohere) |
+| TGI | [TGI Section](#tgi) |
+| VLLM | [VLLM Section](#vllm) |
+
+## OpenAI
+
+### Usage
+
+```python
+lm = dspy.OpenAI(model='gpt-3.5-turbo')
+```
+
+### Constructor
+
+The constructor initializes the base class `LM` and verifies the provided arguments like the `api_provider`, `api_key`, and `api_base` to set up OpenAI request retrieval. The `kwargs` attribute is initialized with default values for relevant text generation parameters needed for communicating with the GPT API, such as `temperature`, `max_tokens`, `top_p`, `frequency_penalty`, `presence_penalty`, and `n`.
+
+```python
+class OpenAI(LM):
+ def __init__(
+ self,
+ model: str = "text-davinci-002",
+ api_key: Optional[str] = None,
+ api_provider: Literal["openai", "azure"] = "openai",
+ model_type: Literal["chat", "text"] = None,
+ **kwargs,
+ ):
+```
+
+
+
+**Parameters:**
+- `api_key` (_Optional[str]_, _optional_): API provider authentication token. Defaults to None.
+- `api_provider` (_Literal["openai", "azure"]_, _optional_): API provider to use. Defaults to "openai".
+- `model_type` (_Literal["chat", "text"]_): Specified model type to use.
+- `**kwargs`: Additional language model arguments to pass to the API provider.
+
+### Methods
+
+#### `__call__(self, prompt: str, only_completed: bool = True, return_sorted: bool = False, **kwargs) -> List[Dict[str, Any]]`
+
+Retrieves completions from OpenAI by calling `request`.
+
+Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response.
+
+After generation, the completions are post-processed based on the `model_type` parameter. If the parameter is set to 'chat', the generated content look like `choice["message"]["content"]`. Otherwise, the generated text will be `choice["text"]`.
+
+**Parameters:**
+- `prompt` (_str_): Prompt to send to OpenAI.
+- `only_completed` (_bool_, _optional_): Flag to return only completed responses and ignore completion due to length. Defaults to True.
+- `return_sorted` (_bool_, _optional_): Flag to sort the completion choices using the returned averaged log-probabilities. Defaults to False.
+- `**kwargs`: Additional keyword arguments for completion request.
+
+**Returns:**
+- `List[Dict[str, Any]]`: List of completion choices.
+
+## Cohere
+
+### Usage
+
+```python
+lm = dsp.Cohere(model='command-xlarge-nightly')
+```
+
+### Constructor
+
+The constructor initializes the base class `LM` and verifies the `api_key` to set up Cohere request retrieval.
+
+```python
+class Cohere(LM):
+ def __init__(
+ self,
+ model: str = "command-xlarge-nightly",
+ api_key: Optional[str] = None,
+ stop_sequences: List[str] = [],
+ ):
+```
+
+**Parameters:**
+- `model` (_str_): Cohere pretrained models. Defaults to `command-xlarge-nightly`.
+- `api_key` (_Optional[str]_, _optional_): API provider from Cohere. Defaults to None.
+- `stop_sequences` (_List[str]_, _optional_): List of stopping tokens to end generation.
+
+### Methods
+
+Refer to [`dspy.OpenAI`](#openai) documentation.
+
+## TGI
+
+### Usage
+
+```python
+lm = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
+```
+
+### Prerequisites
+
+Refer to the [Text Generation-Inference Server](https://github.com/stanfordnlp/dspy/blob/local_models_docs/docs/using_local_models.md#text-generation-inference-server) section of the `Using Local Models` documentation.
+
+### Constructor
+
+The constructor initializes the `HFModel` base class and configures the client for communicating with the TGI server. It requires a `model` instance, communication `port` for the server, and the `url` for the server to host generate requests. Additional configuration can be provided via keyword arguments in `**kwargs`.
+
+```python
+class HFClientTGI(HFModel):
+ def __init__(self, model, port, url="http://future-hgx-1", **kwargs):
+```
+
+**Parameters:**
+- `model` (_HFModel_): Instance of Hugging Face model connected to the TGI server.
+- `port` (_int_): Port for TGI server.
+- `url` (_str_): Base URL where the TGI server is hosted.
+- `**kwargs`: Additional keyword arguments to configure the client.
+
+### Methods
+
+Refer to [`dspy.OpenAI`](#openai) documentation.
+
+## VLLM
+
+### Usage
+
+```python
+lm = dspy.HFClientVLLM(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
+```
+
+### Prerequisites
+
+Refer to the [vLLM Server](https://github.com/stanfordnlp/dspy/blob/local_models_docs/docs/using_local_models.md#vllm-server) section of the `Using Local Models` documentation.
+
+### Constructor
+
+Refer to [`dspy.TGI`](#tgi) documentation. Replace with `HFClientVLLM`.
+
+### Methods
+
+Refer to [`dspy.OpenAI`](#openai) documentation.
\ No newline at end of file
diff --git a/docs/modules.md b/docs/modules.md
new file mode 100644
index 000000000..3fe302c09
--- /dev/null
+++ b/docs/modules.md
@@ -0,0 +1,195 @@
+# dspy.Modules Documentation
+
+This documentation provides an overview of the DSPy Modules.
+
+## DSPy Modules
+
+| Module | Jump To |
+| --- | --- |
+| Predict | [Predict Section](#dspypredict) |
+| Retrieve | [Retrieve Section](#dspyretrieve) |
+| ChainOfThought | [ChainOfThought Section](#dspychainofthought) |
+
+## dspy.Predict
+
+### Constructor
+
+The constructor initializes the `Predict` class and sets up its attributes, taking in the `signature` and additional config options. If the `signature` is a string, it processes the input and output fields, generates instructions, and creates a template for the specified `signature` type.
+
+```python
+class Predict(Parameter):
+ def __init__(self, signature, **config):
+ self.stage = random.randbytes(8).hex()
+ self.signature = signature
+ self.config = config
+ self.reset()
+
+ if isinstance(signature, str):
+ inputs, outputs = signature.split("->")
+ inputs, outputs = inputs.split(","), outputs.split(",")
+ inputs, outputs = [field.strip() for field in inputs], [field.strip() for field in outputs]
+
+ assert all(len(field.split()) == 1 for field in (inputs + outputs))
+
+ inputs_ = ', '.join([f"`{field}`" for field in inputs])
+ outputs_ = ', '.join([f"`{field}`" for field in outputs])
+
+ instructions = f"""Given the fields {inputs_}, produce the fields {outputs_}."""
+
+ inputs = {k: InputField() for k in inputs}
+ outputs = {k: OutputField() for k in outputs}
+
+ for k, v in inputs.items():
+ v.finalize(k, infer_prefix(k))
+
+ for k, v in outputs.items():
+ v.finalize(k, infer_prefix(k))
+
+ self.signature = dsp.Template(instructions, **inputs, **outputs)
+```
+
+**Parameters:**
+- `signature` (_Any_): Signature of predictive model.
+- `**config` (_dict_): Additional configuration parameters for model.
+
+### Method
+
+#### `__call__(self, **kwargs)`
+
+This method serves as a wrapper for the `forward` method. It allows making predictions using the `Predict` class by providing keyword arguments.
+
+**Paramters:**
+- `**kwargs`: Keyword arguments required for prediction.
+
+**Returns:**
+- The result of `forward` method.
+
+### Examples
+
+```python
+#Define a simple signature for basic question answering
+class BasicQA(dspy.Signature):
+ """Answer questions with short factoid answers."""
+ question = dspy.InputField()
+ answer = dspy.OutputField(desc="often between 1 and 5 words")
+
+#Pass signature to Predict module
+generate_answer = dspy.Predict(BasicQA)
+
+# Call the predictor on a particular input.
+question='What is the color of the sky?'
+pred = generate_answer(question=question)
+
+print(f"Question: {question}")
+print(f"Predicted Answer: {pred.answer}")
+```
+
+
+## dspy.Retrieve
+
+### Constructor
+
+The constructor initializes the `Retrieve` class and sets up its attributes, taking in `k` number of retrieval passages to return for a query.
+
+```python
+class Retrieve(Parameter):
+ def __init__(self, k=3):
+ self.stage = random.randbytes(8).hex()
+ self.k = k
+```
+
+**Parameters:**
+- `k` (_Any_): Number of retrieval responses
+
+### Method
+
+#### `__call__(self, *args, **kwargs):`
+
+This method serves as a wrapper for the `forward` method. It allows making retrievals on an input query using the `Retrieve` class.
+
+**Parameters:**
+- `**args`: Arguments required for retrieval.
+- `**kwargs`: Keyword arguments required for retrieval.
+
+**Returns:**
+- The result of the `forward` method.
+
+### Examples
+
+```python
+query='When was the first FIFA World Cup held?'
+
+# Call the retriever on a particular query.
+retrieve = dspy.Retrieve(k=3)
+topK_passages = retrieve(query).passages
+
+print(f"Top {retrieve.k} passages for question: {query} \n", '-' * 30, '\n')
+
+for idx, passage in enumerate(topK_passages):
+ print(f'{idx+1}]', passage, '\n')
+```
+
+# dspy.ChainOfThought
+
+The constructor initializes the `ChainOfThought` class and sets up its attributes. It inherits from the `Predict` class and adds specific functionality for chain of thought processing.
+
+Internally, the class initializes the `activated` attribute to indicate if chain of thought processing has been selected. It extends the `signature` to include additional reasoning steps and an updated `rationale_type` when chain of thought processing is activated.
+
+```python
+class ChainOfThought(Predict):
+ def __init__(self, signature, rationale_type=None, activated=True, **config):
+ super().__init__(signature, **config)
+
+ self.activated = activated
+
+ signature = self.signature
+ *keys, last_key = signature.kwargs.keys()
+
+ DEFAULT_RATIONALE_TYPE = dsp.Type(prefix="Reasoning: Let's think step by step in order to",
+ desc="${produce the " + last_key + "}. We ...")
+
+ rationale_type = rationale_type or DEFAULT_RATIONALE_TYPE
+
+ extended_kwargs = {key: signature.kwargs[key] for key in keys}
+ extended_kwargs.update({'rationale': rationale_type, last_key: signature.kwargs[last_key]})
+
+ self.extended_signature = dsp.Template(signature.instructions, **extended_kwargs)
+```
+
+**Parameters:**
+- `signature` (_Any_): Signature of predictive model.
+- `rationale_type` (_dsp.Type_, _optional_): Rationale type for reasoning steps. Defaults to `None`.
+- `activated` (_bool_, _optional_): Flag for activated chain of thought processing. Defaults to `True`.
+- `**config` (_dict_): Additional configuration parameters for model.
+
+### Method
+
+#### `forward(self, **kwargs)`
+
+This method extends the parent `Predict` class' forward pass while updating the signature when chain of thought reasoning is activated or if the language model is a GPT3 model.
+
+**Parameters:**
+- `**kwargs`: Keyword arguments required for prediction.
+
+**Returns:**
+- The result of the `forward` method.
+
+### Examples
+
+```python
+#Define a simple signature for basic question answering
+class BasicQA(dspy.Signature):
+ """Answer questions with short factoid answers."""
+ question = dspy.InputField()
+ answer = dspy.OutputField(desc="often between 1 and 5 words")
+
+#Pass signature to ChainOfThought module
+generate_answer = dspy.ChainOfThought(BasicQA)
+
+# Call the predictor on a particular input.
+question='What is the color of the sky?'
+pred = generate_answer(question=question)
+
+print(f"Question: {question}")
+print(f"Predicted Answer: {pred.answer}")
+```
\ No newline at end of file
diff --git a/docs/retrieval_models_client.md b/docs/retrieval_models_client.md
new file mode 100644
index 000000000..4dfc5add7
--- /dev/null
+++ b/docs/retrieval_models_client.md
@@ -0,0 +1,94 @@
+# Retriever Modules Documentation
+
+This documentation provides an overview of the DSPy Retrieval Model Clients.
+
+## Supported LM Clients
+
+| LM Client | Jump To |
+| --- | --- |
+| ColBERTv2 | [ColBERTv2 Section](#ColBERTv2) |
+| AzureCognitiveSearch | [AzureCognitiveSearch Section](#AzureCognitiveSearch) |
+
+## ColBERTv2
+
+### Quickstart
+
+```python
+import dspy
+
+colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')
+
+retrieval_response = colbertv2_wiki17_abstracts('When was the first FIFA World Cup held?', k=5)
+
+for result in retrieval_response:
+ print("Text:", result['text'], "\n")
+```
+
+
+### Constructor
+
+The constructor initializes the `ColBERTv2` class instance and sets up the request parameters for interacting with the ColBERTv2 server.
+
+```python
+class ColBERTv2:
+ def __init__(
+ self,
+ url: str = "http://0.0.0.0",
+ port: Optional[Union[str, int]] = None,
+ post_requests: bool = False,
+ ):
+```
+
+**Parameters:**
+- `url` (_str_): URL for ColBERTv2 server.
+- `port` (_Union[str, int]_, _Optional_): Port endpoint for ColBERTv2 server. Defaults to `None`.
+- `post_requests` (_bool_, _Optional_): Flag for using HTTP POST requests. Defaults to `False`.
+
+### Methods
+
+#### `__call__(self, query: str, k: int = 10, simplify: bool = False) -> Union[list[str], list[dotdict]]`
+
+Enables making queries to the ColBERTv2 server for retrieval. Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response. The function handles the retrieval of the top-k passages based on the provided query.
+
+**Parameters:**
+- `query` (_str_): Query string used for retrieval.
+- `k` (_int_, _optional_): Number of passages to retrieve. Defaults to 10.
+- `simplify` (_bool_, _optional_): Flag for simplifying output to a list of strings. Defaults to False.
+
+**Returns:**
+- `Union[list[str], list[dotdict]]`: Depending on `simplify` flag, either a list of strings representing the passage content (`True`) or a list of `dotdict` instances containing passage details (`False`).
+
+## AzureCognitiveSearch
+
+### Quickstart
+
+#TODO
+
+### Constructor
+
+The constructor initializes an instance of the `AzureCognitiveSearch` class and sets up parameters for sending queries and retreiving results with the Azure Cognitive Search server.
+
+```python
+class AzureCognitiveSearch:
+ def __init__(
+ self,
+ search_service_name: str,
+ search_api_key: str,
+ search_index_name: str,
+ field_text: str,
+ field_score: str, # required field to map with "score" field in dsp framework
+ ):
+```
+
+**Parameters:**
+- `search_service_name` (_str_): Name of Azure Cognitive Search server.
+- `search_api_key` (_str_): API Authentication token for accessing Azure Cognitive Search server.
+- `search_index_name` (_str_): Name of search index in the Azure Cognitive Search server.
+- `field_text` (_str_): Field name that maps to DSP "content" field.
+- `field_score` (_str_): Field name that maps to DSP "score" field.
+
+### Methods
+
+Refer to [ColBERTv2](#ColBERTv2) documentation. Keep in mind there is no `simplify` flag for AzureCognitiveSearch.
+
+AzureCognitiveSearch supports sending queries and processing the received results, mapping content and scores to a correct format for the Azure Cognitive Search server.
\ No newline at end of file
diff --git a/docs/teleprompters.md b/docs/teleprompters.md
new file mode 100644
index 000000000..610922007
--- /dev/null
+++ b/docs/teleprompters.md
@@ -0,0 +1,238 @@
+# Teleprompters Documentation
+
+Teleprompters are powerful optimizers (included in DSPy) that can learn to bootstrap and select effective prompts for the modules of any program. (The "tele-" in the name means "at a distance", i.e., automatic prompting at a distance.)
+
+This documentation provides an overview of the DSPy Teleprompters.
+
+## Teleprompters
+
+| Module | Jump To |
+| --- | --- |
+| LabeledFewShot | [LabeledFewShot Section](#telepromptlabeledfewshot) |
+| BootstrapFewShot | [BootstrapFewShot Section](#telepromptbootstrapfewshot) |
+| BootstrapFewShotWithRandomSearch | [BootstrapFewShotWithRandomSearch Section](#telepromptbootstrapfewshotwithrandomsearch) |
+| BootstrapFinetune | [BootstrapFinetune Section](#telepromptbootstrapfinetune) |
+
+## teleprompt.LabeledFewShot
+
+### Constructor
+
+The constructor initializes the `LabeledFewShot` class and sets up its attributes, particularly defining `k` number of samples to be used by the predictor.
+
+```python
+class LabeledFewShot(Teleprompter):
+ def __init__(self, k=16):
+ self.k = k
+```
+
+**Parameters:**
+- `k` (_int_): Number of samples to be used for each predictor. Defaults to 16.
+
+### Method
+
+#### `compile(self, student, *, trainset)`
+
+This method compiles the `LabeledFewShot` instance by configuring the `student` predictor. It assigns subsets of the `trainset` in each student's predictor's `demos` attribute. If the `trainset` is empty, the method returns the original `student`.
+
+**Parameters:**
+- `student` (_Teleprompter_): Student predictor to be compiled.
+- `trainset` (_list_): Training dataset for compiling with student predictor.
+
+**Returns:**
+- The compiled `student` predictor with assigned training samples for each predictor or the original `student` if the `trainset` is empty.
+
+### Example
+
+```python
+import dspy
+
+#Assume defined trainset
+class RAG(dspy.Module):
+ def __init__(self, num_passages=3):
+ super().__init__()
+
+ #declare retrieval and predictor modules
+ self.retrieve = dspy.Retrieve(k=num_passages)
+ self.generate_answer = dspy.ChainOfThought(GenerateAnswer)
+
+ #flow for answering questions using predictor and retrieval modules
+ def forward(self, question):
+ context = self.retrieve(question).passages
+ prediction = self.generate_answer(context=context, question=question)
+ return dspy.Prediction(context=context, answer=prediction.answer)
+
+#Define teleprompter
+teleprompter = LabeledFewShot()
+
+# Compile!
+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)
+```
+
+## teleprompt.BootstrapFewShot
+
+### Constructor
+
+The constructor initializes the `BootstrapFewShot` class and sets up parameters for bootstrapping.
+
+```python
+class BootstrapFewShot(Teleprompter):
+ def __init__(self, metric=None, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1):
+ self.metric = metric
+ self.teacher_settings = teacher_settings
+
+ self.max_bootstrapped_demos = max_bootstrapped_demos
+ self.max_labeled_demos = max_labeled_demos
+ self.max_rounds = max_rounds
+```
+
+**Parameters:**
+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.
+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.
+- `max_bootstrapped_demos` (_int_, _optional_): Maximum number of bootstrapped demonstrations per predictor. Defaults to 4.
+- `max_labeled_demos` (_int_, _optional_): Maximum number of labeled demonstrations per predictor. Defaults to 16.
+- `max_rounds` (_int_, _optional_): Maximum number of bootstrapping rounds. Defaults to 1.
+
+### Method
+
+#### `compile(self, student, *, teacher=None, trainset, valset=None)`
+
+This method compiles the BootstrapFewShot instance by performing bootstrapping to refine the student predictor.
+
+This process includes preparing the student and teacher predictors, which involves creating predictor copies, verifying the student predictor is uncompiled, and compiling the teacher predictor with labeled demonstrations via LabeledFewShot if the teacher predictor hasn't been compiled.
+
+The next stage involves preparing predictor mappings by validating that both the student and teacher predictors have the same program structure and the same signatures but are different objects.
+
+The final stage is performing the bootstrapping iterations.
+
+**Parameters:**
+- `student` (_Teleprompter_): Student predictor to be compiled.
+- `teacher` (_Teleprompter_, _optional_): Teacher predictor used for bootstrapping. Defaults to `None`.
+- `trainset` (_list_): Training dataset used in bootstrapping.
+- `valset` (_list_, _optional_): Validation dataset used in compilation. Defaults to `None`.
+
+**Returns:**
+- The compiled `student` predictor after bootstrapping with refined demonstrations.
+
+### Example
+
+```python
+#Assume defined trainset
+#Assume defined RAG class
+...
+
+#Define teleprompter and include teacher
+teacher = dspy.OpenAI(model='gpt-3.5-turbo', api_key = openai.api_key, api_provider = "openai", model_type = "chat")
+teleprompter = BootstrapFewShot(teacher_settings=dict({'lm': teacher}))
+
+# Compile!
+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)
+```
+
+## teleprompt.BootstrapFewShotWithRandomSearch
+
+### Constructor
+
+The constructor initializes the `BootstrapFewShotWithRandomSearch` class and sets up its attributes. It inherits from the `BootstrapFewShot` class and introduces additional attributes for the random search process.
+
+```python
+class BootstrapFewShotWithRandomSearch(BootstrapFewShot):
+ def __init__(self, metric, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, num_candidate_programs=16, num_threads=6):
+ self.metric = metric
+ self.teacher_settings = teacher_settings
+ self.max_rounds = max_rounds
+
+ self.num_threads = num_threads
+
+ self.min_num_samples = 1
+ self.max_num_samples = max_bootstrapped_demos
+ self.num_candidate_sets = num_candidate_programs
+ self.max_num_traces = 1 + int(max_bootstrapped_demos / 2.0 * self.num_candidate_sets)
+
+ self.max_bootstrapped_demos = self.max_num_traces
+ self.max_labeled_demos = max_labeled_demos
+
+ print("Going to sample between", self.min_num_samples, "and", self.max_num_samples, "traces per predictor.")
+ print("Going to sample", self.max_num_traces, "traces in total.")
+ print("Will attempt to train", self.num_candidate_sets, "candidate sets.")
+```
+
+**Parameters:**
+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.
+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.
+- `max_bootstrapped_demos` (_int_, _optional_): Maximum number of bootstrapped demonstrations per predictor. Defaults to 4.
+- `max_labeled_demos` (_int_, _optional_): Maximum number of labeled demonstrations per predictor. Defaults to 16.
+- `max_rounds` (_int_, _optional_): Maximum number of bootstrapping rounds. Defaults to 1.
+- `num_candidate_programs` (_int_): Number of candidate programs to generate during random search.
+- `num_threads` (_int_): Number of threads used for evaluation during random search.
+
+### Method
+
+Refer to [teleprompt.BootstrapFewShot](#telepromptbootstrapfewshot) documentation.
+
+## Example
+
+```python
+#Assume defined trainset
+#Assume defined RAG class
+...
+
+#Define teleprompter and include teacher
+teacher = dspy.OpenAI(model='gpt-3.5-turbo', api_key = openai.api_key, api_provider = "openai", model_type = "chat")
+teleprompter = BootstrapFewShotWithRandomSearch(teacher_settings=dict({'lm': teacher}))
+
+# Compile!
+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)
+```
+
+## teleprompt.BootstrapFinetune
+
+### Constructor
+
+### `__init__(self, metric=None, teacher_settings={}, multitask=True)`
+
+The constructor initializes a `BootstrapFinetune` instance and sets up its attributes. It defines the teleprompter as a `BootstrapFewShot` instance for the finetuning compilation.
+
+```python
+class BootstrapFinetune(Teleprompter):
+ def __init__(self, metric=None, teacher_settings={}, multitask=True):
+```
+
+**Parameters:**
+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.
+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.
+- `multitask` (_bool_, _optional_): Enable multitask fine-tuning. Defaults to `True`.
+
+### Method
+
+#### `compile(self, student, *, teacher=None, trainset, valset=None, target='t5-large', bsize=12, accumsteps=1, lr=5e-5, epochs=1, bf16=False)`
+
+This method first compiles for bootstrapping with the `BootstrapFewShot` teleprompter. It then prepares fine-tuning data by generating prompt-completion pairs for training and performs finetuning. After compilation, the LMs are set to the finetuned models and the method returns a compiled and fine-tuned predictor.
+
+**Parameters:**
+- `student` (_Predict_): Student predictor to be fine-tuned.
+- `teacher` (_Predict_, _optional_): Teacher predictor to help with fine-tuning. Defaults to `None`.
+- `trainset` (_list_): Training dataset for fine-tuning.
+- `valset` (_list_, _optional_): Validation dataset for fine-tuning. Defaults to `None`.
+- `target` (_str_, _optional_): Target model for fine-tuning. Defaults to `'t5-large'`.
+- `bsize` (_int_, _optional_): Batch size for training. Defaults to `12`.
+- `accumsteps` (_int_, _optional_): Gradient accumulation steps. Defaults to `1`.
+- `lr` (_float_, _optional_): Learning rate for fine-tuning. Defaults to `5e-5`.
+- `epochs` (_int_, _optional_): Number of training epochs. Defaults to `1`.
+- `bf16` (_bool_, _optional_): Enable mixed-precision training with BF16. Defaults to `False`.
+
+**Returns:**
+- `compiled2` (_Predict_): A compiled and fine-tuned `Predict` instance.
+
+### Example
+
+```python
+#Assume defined trainset
+#Assume defined RAG class
+...
+
+#Define teleprompter
+teleprompter = BootstrapFinetune(teacher_settings=dict({'lm': teacher}))
+
+# Compile!
+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset, target='google/flan-t5-base')
+```
\ No newline at end of file
diff --git a/docs/using_local_models.md b/docs/using_local_models.md
new file mode 100644
index 000000000..fc201b0d2
--- /dev/null
+++ b/docs/using_local_models.md
@@ -0,0 +1,154 @@
+# Using local models within DSPy
+
+DSPy supports various methods including `built-in wrappers`, `server integration`, and `external package integration` for model loading. This documentation provides a concise introduction on how to load in models within DSPy extending these capabilities for your specific needs.
+
+## Local Model Loaders
+
+| Loaders | Jump To |
+| --- | --- |
+| HFModel | [HFModel Section](#hfmodel) |
+| Cohere | [Cohere Section](#cohere) |
+| TGI | [TGI Section](#tgi) |
+| VLLM | [VLLM Section](#vllm) |
+
+
+# HFModel
+
+Initialize `HFModel` within your program with the desired model to load in. Here's an example call:
+
+ ```python
+ llama = dspy.HFModel(model = 'meta-llama/Llama-2-7b-hf')
+ ```
+
+# Text-Generation-Inference Server
+
+## Prerequisites
+
+- Docker must be installed on your system. If you don't have Docker installed, you can get it from [here](https://docs.docker.com/get-docker/).
+
+## Setting up the Text-Generation-Inference Server
+
+1. Clone the Text-Generation-Inference repository from GitHub by executing the following command:
+
+ ```
+ git clone https://github.com/huggingface/text-generation-inference.git
+ ```
+
+2. Change into the cloned repository directory:
+
+ ```
+ cd text-generation-inference
+ ```
+
+3. Execute the Docker command under the "Get Started" section to run the server:
+
+ ```
+ model=meta-llama/Llama-2-7b-hf # set to the specific Hugging Face model ID you wish to use.
+ num_shard=2 # set to the number of shards you wish to use.
+ volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
+
+ docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:0.9 --model-id $model --num-shard $num_shard
+ ```
+
+ This command will start the server and make it accessible at `http://localhost:8080`.
+
+If you want to connect to [Meta Llama 2 models](https://huggingface.co/meta-llama), make sure to use version 9.3 (or higher) of the docker image (ghcr.io/huggingface/text-generation-inference:0.9.3) and pass in your huggingface token as an environment variable.
+
+ docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data -e HUGGING_FACE_HUB_TOKEN={your_token} ghcr.io/huggingface/text-generation-inference:0.9.3 --model-id $model --num-shard $num_shard
+
+## Sending requests to the server
+
+After setting up the text-generation-inference server and ensuring that it displays "Connected" when it's running, you can interact with it using the `HFClientTGI`.
+
+Initialize the `HFClientTGI` within your program with the desired parameters. Here is an example call:
+
+ ```python
+ lm = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
+ ```
+
+ Customize the `model`, `port`, and `url` according to your requirements. The `model` parameter should be set to the specific Hugging Face model ID you wish to use.
+
+
+### FAQs
+
+1. If your model doesn't require any shards, you still need to set a value for `num_shard`, but you don't need to include the parameter `--num-shard` on the command line.
+
+2. If your model runs into any "token exceeded" issues, you can set the following parameters on the command line to adjust the input length and token limit:
+ - `--max-input-length`: Set the maximum allowed input length for the text.
+ - `--max-total-tokens`: Set the maximum total tokens allowed for text generation.
+
+Please refer to the [official Text-Generation-Inference repository](https://github.com/huggingface/text-generation-inference) for more detailed information and documentation.
+
+
+# vLLM Server
+
+## Setting up the vLLM Server
+
+Follow these steps to set up the vLLM Server:
+
+1. Build the server from source by following the instructions provided in the [Build from Source guide](https://vllm.readthedocs.io/en/latest/getting_started/installation.html#build-from-source).
+
+2. Start the server by running the following command, and specify your desired model, host, and port using the appropriate arguments. The default server address is http://localhost:8000.
+
+ Example command:
+ ```
+ python -m vllm.entrypoints.api_server --model mosaicml/mpt-7b --port 8000
+ ```
+
+This will launch the vLLM server.
+
+## Sending requests to the vLLM server
+
+After setting up the vLLM server and ensuring that it displays "Connected" when it's running, you can interact with it using the `HFClientVLLM`.
+
+Initialize the `HFClientVLLM` within your program with the desired parameters. Here is an example call:
+
+ ```python
+ lm = dspy.HFClientVLLM(model="mosaicml/mpt-7b", port=8000, url="http://localhost")
+ ```
+
+ Customize the `model`, `port`, `url`, and `max_tokens` according to your requirements. The `model` parameter should be set to the specific Hugging Face model ID you wish to use.
+
+Please refer to the [official vLLM repository](https://github.com/vllm-project/vllm) for more detailed information and documentation.
+
+# MLC LLM
+
+## Prerequisites
+
+1. Install the required packages using the following commands:
+
+ ```shell
+ pip install --no-deps --pre --force-reinstall mlc-ai-nightly-cu118 mlc-chat-nightly-cu118 -f https://mlc.ai/wheels
+ pip install transformers
+ git lfs install
+ ```
+
+ Adjust the pip wheels according to your OS/platform by referring to the provided commands in [MLC packages](https://mlc.ai/package/).
+
+## Running MLC Llama-2 models
+
+1. Create a directory for prebuilt models:
+
+ ```shell
+ mkdir -p dist/prebuilt
+ ```
+
+2. Clone the necessary libraries from the repository:
+
+ ```shell
+ git clone https://github.com/mlc-ai/binary-mlc-llm-libs.git dist/prebuilt/lib
+ cd dist/prebuilt
+ ```
+
+3. Choose a Llama-2 model from [MLC LLMs](https://huggingface.co/mlc-ai) and clone the model repository:
+
+ ```shell
+ git clone https://huggingface.co/mlc-ai/mlc-chat-Llama-2-7b-chat-hf-q4f16_1
+ ```
+
+4. Initialize the `ChatModuleClient` within your program with the desired parameters. Here's an example call:
+
+ ```python
+ llama = dspy.ChatModuleClient(model='dist/prebuilt/mlc-chat-Llama-2-7b-chat-hf-q4f16_1', model_path='dist/prebuilt/lib/Llama-2-7b-chat-hf-q4f16_1-cuda.so')
+ ```
+Please refer to the [official MLC repository](https://github.com/mlc-ai/mlc-llm) for more detailed information and [documentation](https://mlc.ai/mlc-llm/docs/get_started/try_out.html).
diff --git a/dsp/modules/hf_client.py b/dsp/modules/hf_client.py
index 34aa18da7..e368800a6 100644
--- a/dsp/modules/hf_client.py
+++ b/dsp/modules/hf_client.py
@@ -27,6 +27,7 @@ from dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory, cache_turn
# from dsp.modules.adapter import TurboAdapter, DavinciAdapter, LlamaAdapter
+
class HFClientTGI(HFModel):
def __init__(self, model, port, url="http://future-hgx-1", **kwargs):
super().__init__(model=model, is_client=True)
@@ -44,53 +45,59 @@ class HFClientTGI(HFModel):
def _generate(self, prompt, **kwargs):
kwargs = {**self.kwargs, **kwargs}
-
+
payload = {
- "inputs": prompt,
- "parameters": {
- "do_sample": kwargs["n"] > 1,
- "best_of": kwargs["n"],
- "details": kwargs["n"] > 1,
- # "max_new_tokens": kwargs.get('max_tokens', kwargs.get('max_new_tokens', 75)),
- "stop": ["\n", "\n\n"],
- **kwargs,
- }
+ "inputs": prompt,
+ "parameters": {
+ "do_sample": kwargs["n"] > 1,
+ "best_of": kwargs["n"],
+ "details": kwargs["n"] > 1,
+ # "max_new_tokens": kwargs.get('max_tokens', kwargs.get('max_new_tokens', 75)),
+ "stop": ["\n", "\n\n"],
+ **kwargs,
+ },
}
- payload['parameters'] = openai_to_hf(**payload['parameters'])
+ payload["parameters"] = openai_to_hf(**payload["parameters"])
- payload['parameters']['temperature'] = max(0.1, payload['parameters']['temperature'])
+ payload["parameters"]["temperature"] = max(
+ 0.1, payload["parameters"]["temperature"]
+ )
# print(payload['parameters'])
-
+
# response = requests.post(self.url + "/generate", json=payload, headers=self.headers)
- response = send_hftgi_request_v00(self.url + "/generate", json=payload, headers=self.headers)
+ response = send_hftgi_request_v00(
+ self.url + "/generate", json=payload, headers=self.headers
+ )
try:
json_response = response.json()
# completions = json_response["generated_text"]
- completions = [json_response['generated_text']]
-
- if 'details' in json_response and 'best_of_sequences' in json_response['details']:
- completions += [x['generated_text'] for x in json_response['details']['best_of_sequences']]
-
- response = {
- "prompt": prompt,
- "choices": [
- {"text": c} for c in completions
- ]
- }
+ completions = [json_response["generated_text"]]
+
+ if (
+ "details" in json_response
+ and "best_of_sequences" in json_response["details"]
+ ):
+ completions += [
+ x["generated_text"]
+ for x in json_response["details"]["best_of_sequences"]
+ ]
+
+ response = {"prompt": prompt, "choices": [{"text": c} for c in completions]}
return response
except Exception as e:
- print("Failed to parse JSON response:", response.text)
- raise Exception("Received invalid JSON response from server")
+ print("Failed to parse JSON response:", response.text)
+ raise Exception("Received invalid JSON response from server")
@CacheMemory.cache
def send_hftgi_request_v00(arg, **kwargs):
return requests.post(arg, **kwargs)
+
class ChatModuleClient(HFModel):
def __init__(self, model, model_path):
super().__init__(model=model, is_client=True)
@@ -98,7 +105,9 @@ class ChatModuleClient(HFModel):
from mlc_chat import ChatModule
from mlc_chat import ChatConfig
- self.cm = ChatModule(model=model, lib_path=model_path, chat_config=ChatConfig(conv_template="LM"))
+ self.cm = ChatModule(
+ model=model, lib_path=model_path, chat_config=ChatConfig(conv_template="LM")
+ )
def _generate(self, prompt, **kwargs):
output = self.cm.generate(
@@ -106,11 +115,8 @@ class ChatModuleClient(HFModel):
)
try:
completions = [{"text": output}]
- response = {
- "prompt": prompt,
- "choices": completions
- }
+ response = {"prompt": prompt, "choices": completions}
return response
except Exception as e:
- print("Failed to parse output:", response.text)
- raise Exception("Received invalid output")
+ print("Failed to parse output:", response.text)
+ raise Exception("Received invalid output")