You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

AutoGen-OpenAI.md 5.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # AutoGen - OpenAI
  2. FLAML offers a cost-effective hyperparameter optimization technique [EcoOptiGen](https://arxiv.org/abs/2303.04673) for tuning Large Language Models. Our study finds that tuning hyperparameters can significantly improve the utility of them.
  3. In this example, we will tune several hyperparameters for the OpenAI's completion API, including the temperature, prompt and n (number of completions), to optimize the inference performance for a code generation task.
  4. ### Prerequisites
  5. Install the [autogen,blendsearch] option.
  6. ```bash
  7. pip install "flaml[autogen,blendsearch] datasets"
  8. ```
  9. Setup your OpenAI key:
  10. ```python
  11. import os
  12. if "OPENAI_API_KEY" not in os.environ:
  13. os.environ["OPENAI_API_KEY"] = "<your OpenAI API key here>"
  14. ```
  15. If you use Azure OpenAI, set up Azure using the following code:
  16. ```python
  17. import openai
  18. openai.api_type = "azure"
  19. openai.api_base = "https://<your_endpoint>.openai.azure.com/"
  20. openai.api_version = "2023-03-15-preview" # change if necessary
  21. ```
  22. ### Load the dataset
  23. We use the HumanEval dataset as an example. The dataset contains 164 examples. We use the first 20 for tuning the generation hyperparameters and the remaining for evaluation. In each example, the "prompt" is the prompt string for eliciting the code generation, "test" is the Python code for unit test for the example, and "entry_point" is the function name to be tested.
  24. ```python
  25. import datasets
  26. seed = 41
  27. data = datasets.load_dataset("openai_humaneval")["test"].shuffle(seed=seed)
  28. n_tune_data = 20
  29. tune_data = [
  30. {
  31. "definition": data[x]["prompt"],
  32. "test": data[x]["test"],
  33. "entry_point": data[x]["entry_point"],
  34. }
  35. for x in range(n_tune_data)
  36. ]
  37. test_data = [
  38. {
  39. "definition": data[x]["prompt"],
  40. "test": data[x]["test"],
  41. "entry_point": data[x]["entry_point"],
  42. }
  43. for x in range(n_tune_data, len(data))
  44. ]
  45. ```
  46. ### Define the metric
  47. Before starting tuning, you need to define the metric for the optimization. For each code generation task, we can use the model to generate multiple candidate responses, and then select one from them. If the final selected response can pass a unit test, we consider the task as successfully solved. Then we can define the average success rate on a collection of tasks as the optimization metric.
  48. ```python
  49. from functools import partial
  50. from flaml.autogen.code_utils import eval_function_completions, generate_assertions
  51. eval_with_generated_assertions = partial(
  52. eval_function_completions, assertions=generate_assertions,
  53. )
  54. ```
  55. This function will first generate assertion statements for each problem. Then, it uses the assertions to select the generated responses.
  56. ### Tune the hyperparameters
  57. The tuning will be performed under the specified optimization budgets.
  58. * inference_budget is the target average inference budget per instance in the benchmark. For example, 0.02 means the target inference budget is 0.02 dollars, which translates to 1000 tokens (input + output combined) if the text Davinci model is used.
  59. * optimization_budget is the total budget allowed to perform the tuning. For example, 5 means 5 dollars are allowed in total, which translates to 250K tokens for the text Davinci model.
  60. * num_sumples is the number of different hyperparameter configurations which is allowed to try. The tuning will stop after either num_samples trials or after optimization_budget dollars spent, whichever happens first. -1 means no hard restriction in the number of trials and the actual number is decided by optimization_budget.
  61. Users can specify tuning data, optimization metric, optimization mode, evaluation function, search spaces etc.
  62. ```python
  63. from flaml import oai
  64. config, analysis = oai.Completion.tune(
  65. data=tune_data, # the data for tuning
  66. metric="success", # the metric to optimize
  67. mode="max", # the optimization mode
  68. eval_func=eval_with_generated_assertions, # the evaluation function to return the success metrics
  69. # log_file_name="logs/humaneval.log", # the log file name
  70. inference_budget=0.05, # the inference budget (dollar per instance)
  71. optimization_budget=3, # the optimization budget (dollar in total)
  72. # num_samples can further limit the number of trials for different hyperparameter configurations;
  73. # -1 means decided by the optimization budget only
  74. num_samples=-1,
  75. prompt=[
  76. "{definition}",
  77. "# Python 3{definition}",
  78. "Complete the following Python function:{definition}",
  79. ], # the prompt templates to choose from
  80. stop=[["\nclass", "\ndef", "\nif", "\nprint"], None], # the stop sequences
  81. )
  82. ```
  83. #### Output tuning results
  84. After the tuning, we can print out the optimized config and the result found by FLAML:
  85. ```python
  86. print("optimized config", config)
  87. print("best result on tuning data", analysis.best_result)
  88. ```
  89. #### Make a request with the tuned config
  90. We can apply the tuned config to the request for an instance:
  91. ```python
  92. response = oai.Completion.create(context=tune_data[1], **config)
  93. print(response)
  94. print(eval_with_generated_assertions(oai.Completion.extract_text(response), **tune_data[1]))
  95. ```
  96. #### Evaluate the success rate on the test data
  97. You can use flaml's `oai.Completion.test` to evaluate the performance of an entire dataset with the tuned config.
  98. ```python
  99. result = oai.Completion.test(test_data, **config)
  100. print("performance on test data with the tuned config:", result)
  101. ```
  102. The result will vary with the inference budget and optimization budget.
  103. [Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/autogen_openai_completion.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/autogen_openai_completion.ipynb)