From fe7b7ae7365d056f6453b3c2583bd43597fd6b29 Mon Sep 17 00:00:00 2001 From: Anish Shah Date: Mon, 19 Aug 2024 11:44:28 -0400 Subject: [PATCH] Delete dspy_prompt_optimization.ipynb --- docs/notebooks/dspy_prompt_optimization.ipynb | 434 ------------------ 1 file changed, 434 deletions(-) delete mode 100644 docs/notebooks/dspy_prompt_optimization.ipynb diff --git a/docs/notebooks/dspy_prompt_optimization.ipynb b/docs/notebooks/dspy_prompt_optimization.ipynb deleted file mode 100644 index 94c6b485e15..00000000000 --- a/docs/notebooks/dspy_prompt_optimization.ipynb +++ /dev/null @@ -1,434 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "# Optimizing LLM Workflows Using DSPy and Weave\n", - "\n", - "The [BIG-bench (Beyond the Imitation Game Benchmark)](https://github.com/google/BIG-bench) is a collaborative benchmark intended to probe large language models and extrapolate their future capabilities consisting of more than 200 tasks. The [BIG-Bench Hard (BBH)](https://github.com/suzgunmirac/BIG-Bench-Hard) is a suite of 23 most challenging BIG-Bench tasks that can be quite difficult to be solved using the current generation of language models.\n", - "\n", - "This tutorial demonstrates how we can improve the performance of our LLM workflow implemented on the **causal judgement task** from the BIG-bench Hard benchmark and evaluate our prompting strategies. We will use [DSPy](https://dspy-docs.vercel.app/) for implementing our LLM workflow and optimizing our prompting strategy. We will also use [Weave](../docs/introduction.md) to track our LLM workflow and evaluate our prompting strategies." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Installing the Dependencies\n", - "\n", - "We need the following libraries for this tutorial:\n", - "\n", - "- [DSPy](https://dspy-docs.vercel.app/) for building the LLM workflow and optimizing it.\n", - "- [Weave](../introduction.md) to track our LLM workflow and evaluate our prompting strategies.\n", - "- [datasets](https://huggingface.co/docs/datasets/index) to access the Big-Bench Hard dataset from HuggingFace Hub." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "!pip install -qU dspy-ai weave datasets" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Since we'll be using [OpenAI API](https://openai.com/index/openai-api/) as the LLM Vendor, we will also need an OpenAI API key. You can [sign up](https://platform.openai.com/signup) on the OpenAI platform to get your own API key." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "from getpass import getpass\n", - "\n", - "api_key = getpass(\"Enter you OpenAI API key: \")\n", - "os.environ[\"OPENAI_API_KEY\"] = api_key" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Enable Tracking using Weave\n", - "\n", - "Weave is currently integrated with DSPy, and including [`weave.init`](../docs/reference/python-sdk/weave/index.md) at the start of our code lets us automatically trace our DSPy functions which can be explored in the Weave UI. Check out the [Weave integration docs for DSPy](../docs/guides/integrations/dspy.md) to learn more." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import weave\n", - "\n", - "weave.init(project_name=\"dspy-bigbench-hard\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this tutorial, we use a metadata class inherited from [`weave.Model`](../docs/guides/core-types/models.md) to manage our metadata." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "class Metadata(weave.Model):\n", - " dataset_address: str = \"maveriq/bigbenchhard\"\n", - " big_bench_hard_task: str = \"causal_judgement\"\n", - " num_train_examples: int = 50\n", - " openai_model: str = \"gpt-3.5-turbo\"\n", - " openai_max_tokens: int = 2048\n", - " max_bootstrapped_demos: int = 8\n", - " max_labeled_demos: int = 8\n", - "\n", - "\n", - "metadata = Metadata()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "| ![](../static/img/dspy_prompt_optimiztion/metadata.gif) |\n", - "|---|\n", - "| The `Metadata` objects are automatically versioned and traced when functions consuming them are traced |" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Load the BIG-Bench Hard Dataset\n", - "\n", - "We will load this dataset from HuggingFace Hub, split into training and validation sets, and [publish](../docs/guides/core-types/datasets.md) them on Weave, this will let us version the datasets, and also use [`weave.Evaluation`](../docs/guides/core-types/evaluations.md) to evaluate our prompting strategy." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import dspy\n", - "from datasets import load_dataset\n", - "\n", - "\n", - "@weave.op()\n", - "def get_dataset(metadata: Metadata):\n", - " # load the BIG-Bench Hard dataset corresponding to the task from Huggingface Hug\n", - " dataset = load_dataset(metadata.dataset_address, metadata.big_bench_hard_task)[\n", - " \"train\"\n", - " ]\n", - "\n", - " # create the training and validation datasets\n", - " rows = [{\"question\": data[\"input\"], \"answer\": data[\"target\"]} for data in dataset]\n", - " train_rows = rows[0 : metadata.num_train_examples]\n", - " val_rows = rows[metadata.num_train_examples :]\n", - "\n", - " # create the training and validation examples consisting of `dspy.Example` objects\n", - " dspy_train_examples = [\n", - " dspy.Example(row).with_inputs(\"question\") for row in train_rows\n", - " ]\n", - " dspy_val_examples = [dspy.Example(row).with_inputs(\"question\") for row in val_rows]\n", - "\n", - " # publish the datasets to the Weave, this would let us version the data and use for evaluation\n", - " weave.publish(\n", - " weave.Dataset(\n", - " name=f\"bigbenchhard_{metadata.big_bench_hard_task}_train\", rows=train_rows\n", - " )\n", - " )\n", - " weave.publish(\n", - " weave.Dataset(\n", - " name=f\"bigbenchhard_{metadata.big_bench_hard_task}_val\", rows=val_rows\n", - " )\n", - " )\n", - "\n", - " return dspy_train_examples, dspy_val_examples\n", - "\n", - "\n", - "dspy_train_examples, dspy_val_examples = get_dataset(metadata)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "| ![](../static/img/dspy_prompt_optimiztion/datasets.gif) |\n", - "|---|\n", - "| The datasets, once published, can be explored in the Weave UI |" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The DSPy Program\n", - "\n", - "[DSPy](https://dspy-docs.vercel.app) is a framework that pushes building new LM pipelines away from manipulating free-form strings and closer to programming (composing modular operators to build text transformation graphs) where a compiler automatically generates optimized LM invocation strategies and prompts from a program.\n", - "\n", - "We will use the [`dspy.OpenAI`](https://dspy-docs.vercel.app/api/language_model_clients/OpenAI) abstraction to make LLM calls to [GPT3.5 Turbo](https://platform.openai.com/docs/models/gpt-3-5-turbo)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "system_prompt = \"\"\"\n", - "You are an expert in the field of causal reasoning. You are to analyze the a given question carefully and answer in `Yes` or `No`.\n", - "You should also provide a detailed explanation justifying your answer.\n", - "\"\"\"\n", - "\n", - "llm = dspy.OpenAI(model=\"gpt-3.5-turbo\", system_prompt=system_prompt)\n", - "dspy.settings.configure(lm=llm)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Writing the Causal Reasoning Signature\n", - "\n", - "A [signature](https://dspy-docs.vercel.app/docs/building-blocks/signatures) is a declarative specification of input/output behavior of a [DSPy module](https://dspy-docs.vercel.app/docs/building-blocks/modules) which are task-adaptive components—akin to neural network layers—that abstract any particular text transformation." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from pydantic import BaseModel, Field\n", - "\n", - "\n", - "class Input(BaseModel):\n", - " query: str = Field(description=\"The question to be answered\")\n", - "\n", - "\n", - "class Output(BaseModel):\n", - " answer: str = Field(description=\"The answer for the question\")\n", - " confidence: float = Field(\n", - " ge=0, le=1, description=\"The confidence score for the answer\"\n", - " )\n", - " explanation: str = Field(description=\"The explanation for the answer\")\n", - "\n", - "\n", - "class QuestionAnswerSignature(dspy.Signature):\n", - " input: Input = dspy.InputField()\n", - " output: Output = dspy.OutputField()\n", - "\n", - "\n", - "class CausalReasoningModule(dspy.Module):\n", - " def __init__(self):\n", - " self.prog = dspy.TypedPredictor(QuestionAnswerSignature)\n", - "\n", - " @weave.op()\n", - " def forward(self, question) -> dict:\n", - " return self.prog(input=Input(query=question)).output.dict()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's test our LLM workflow, i.e., the `CausalReasoningModule` on an example from the causal reasoning subset of Big-Bench Hard." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import rich\n", - "\n", - "baseline_module = CausalReasoningModule()\n", - "\n", - "prediction = baseline_module(dspy_train_examples[0][\"question\"])\n", - "rich.print(prediction)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "| ![](../static/img/dspy_prompt_optimiztion/dspy_module_trace.gif) |\n", - "|---|\n", - "| Here's how you can explore the traces of the `CausalReasoningModule` in the Weave UI |" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluating our DSPy Program\n", - "\n", - "Now that we have a baseline prompting strategy, let's evaluate it on our validation set using [`weave.Evaluation`](../docs/guides/core-types/evaluations.md) on a simple metric that matches the predicted answer with the ground truth. Weave will take each example, pass it through your application and score the output on multiple custom scoring functions. By doing this, you'll have a view of the performance of your application, and a rich UI to drill into individual outputs and scores.\n", - "\n", - "First, we need to create a simple weave evaluation scoring function that tells whether the answer from the baseline module's output is the same as the ground truth answer or not. Scoring functions need to have a `model_output` keyword argument, but the other arguments are user defined and are taken from the dataset examples. It will only take the necessary keys by using a dictionary key based on the argument name." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "@weave.op()\n", - "def weave_evaluation_scorer(answer: str, model_output: Output) -> dict:\n", - " return {\"match\": int(answer.lower() == model_output[\"answer\"].lower())}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Next, we can simply define the evaluation and run it." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "validation_dataset = weave.ref(\n", - " f\"bigbenchhard_{metadata.big_bench_hard_task}_val:v0\"\n", - ").get()\n", - "\n", - "evaluation = weave.Evaluation(\n", - " name=\"baseline_causal_reasoning_module\",\n", - " dataset=validation_dataset,\n", - " scorers=[weave_evaluation_scorer],\n", - ")\n", - "\n", - "await evaluation.evaluate(baseline_module.forward)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ":::note\n", - "If you're running from a python script, you can use the following code to run the evaluation:\n", - "\n", - "```python\n", - "import asyncio\n", - "asyncio.run(evaluation.evaluate(baseline_module.forward))\n", - "```\n", - ":::\n", - "\n", - ":::warning\n", - "Running the evaluation causal reasoning dataset will cost approximately $0.24 in OpenAI credits.\n", - ":::" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Optimizing our DSPy Program\n", - "\n", - "Now, that we have a baseline DSPy program, let us try to improve its performance for causal reasoning using a [DSPy teleprompter](https://dspy-docs.vercel.app/docs/building-blocks/optimizers) that can tune the parameters of a DSPy program to maximize the specified metrics. In this tutorial, we use the [BootstrapFewShot](https://dspy-docs.vercel.app/api/category/optimizers) teleprompter." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from dspy.teleprompt import BootstrapFewShot\n", - "\n", - "\n", - "@weave.op()\n", - "def get_optimized_program(model: dspy.Module, metadata: Metadata) -> dspy.Module:\n", - " @weave.op()\n", - " def dspy_evaluation_metric(true, prediction, trace=None):\n", - " return prediction[\"answer\"].lower() == true.answer.lower()\n", - "\n", - " teleprompter = BootstrapFewShot(\n", - " metric=dspy_evaluation_metric,\n", - " max_bootstrapped_demos=metadata.max_bootstrapped_demos,\n", - " max_labeled_demos=metadata.max_labeled_demos,\n", - " )\n", - " return teleprompter.compile(model, trainset=dspy_train_examples)\n", - "\n", - "\n", - "optimized_module = get_optimized_program(baseline_module, metadata)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ":::warning\n", - "Running the evaluation causal reasoning dataset will cost approximately $0.04 in OpenAI credits.\n", - ":::\n", - "\n", - "| ![](../static/img/dspy_prompt_optimiztion/dspy_compile.png) |\n", - "|---|\n", - "| You can explore the traces of the optimization process in the Weave UI. |\n", - "\n", - "Now that we have our optimized program (the optimized prompting strategy), let's evaluate it once again on our validation set and compare it with our baseline DSPy program." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "evaluation = weave.Evaluation(\n", - " name=\"optimized_causal_reasoning_module\",\n", - " dataset=validation_dataset,\n", - " scorers=[weave_evaluation_scorer],\n", - ")\n", - "\n", - "await evaluation.evaluate(optimized_module.forward)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "| ![](../static/img/dspy_prompt_optimiztion/eval_comparison.gif) |\n", - "|---|\n", - "| Comparing the evalution of the baseline program with the optimized one shows that the optimized program answers the causal reasoning questions with siginificantly more accuracy. |" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -}