Commit Β·
c08e081
0
Parent(s):
Duplicate from RamAnanth1/Dolly-v2
Browse filesCo-authored-by: Ram Ananth <RamAnanth1@users.noreply.huggingface.co>
- .gitattributes +34 -0
- README.md +13 -0
- app.py +133 -0
- instruct_pipeline.py +158 -0
- requirements.txt +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Dolly V2
|
| 3 |
+
emoji: π
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 3.24.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
duplicated_from: RamAnanth1/Dolly-v2
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from typing import Iterable
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from gradio.themes.base import Base
|
| 5 |
+
from gradio.themes.utils import colors, fonts, sizes
|
| 6 |
+
from instruct_pipeline import InstructionTextGenerationPipeline
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
theme = gr.themes.Monochrome(
|
| 12 |
+
primary_hue="indigo",
|
| 13 |
+
secondary_hue="blue",
|
| 14 |
+
neutral_hue="slate",
|
| 15 |
+
radius_size=gr.themes.sizes.radius_sm,
|
| 16 |
+
font=[gr.themes.GoogleFont("Open Sans"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
tokenizer = AutoTokenizer.from_pretrained("databricks/dolly-v2-12b", padding_side="left")
|
| 20 |
+
model = AutoModelForCausalLM.from_pretrained("databricks/dolly-v2-12b", device_map="auto", load_in_8bit=True)
|
| 21 |
+
|
| 22 |
+
generate_text = InstructionTextGenerationPipeline(model=model, tokenizer=tokenizer)
|
| 23 |
+
|
| 24 |
+
#generate_text = pipeline(model="databricks/dolly-v2-12b", torch_dtype=torch.bfloat16, trust_remote_code=True, device_map="auto")
|
| 25 |
+
|
| 26 |
+
def generate(instruction):
|
| 27 |
+
response = generate_text(instruction)
|
| 28 |
+
result = ""
|
| 29 |
+
for word in response.split(" "):
|
| 30 |
+
result += word + " "
|
| 31 |
+
yield result
|
| 32 |
+
|
| 33 |
+
examples = [
|
| 34 |
+
"Instead of making a peanut butter and jelly sandwich, what else could I combine peanut butter with in a sandwich? Give five ideas",
|
| 35 |
+
"How do I make a campfire?",
|
| 36 |
+
"Write me a tweet about the release of Dolly 2.0, a new LLM",
|
| 37 |
+
"Explain to me the difference between nuclear fission and fusion.",
|
| 38 |
+
"I'm selling my Nikon D-750, write a short blurb for my ad."
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
def process_example(args):
|
| 42 |
+
for x in generate(args):
|
| 43 |
+
pass
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
css = ".generating {visibility: hidden}"
|
| 47 |
+
|
| 48 |
+
# Based on the gradio theming guide and borrowed from https://huggingface.co/spaces/shivi/dolly-v2-demo
|
| 49 |
+
class SeafoamCustom(Base):
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
*,
|
| 53 |
+
primary_hue: colors.Color | str = colors.emerald,
|
| 54 |
+
secondary_hue: colors.Color | str = colors.blue,
|
| 55 |
+
neutral_hue: colors.Color | str = colors.blue,
|
| 56 |
+
spacing_size: sizes.Size | str = sizes.spacing_md,
|
| 57 |
+
radius_size: sizes.Size | str = sizes.radius_md,
|
| 58 |
+
font: fonts.Font
|
| 59 |
+
| str
|
| 60 |
+
| Iterable[fonts.Font | str] = (
|
| 61 |
+
fonts.GoogleFont("Quicksand"),
|
| 62 |
+
"ui-sans-serif",
|
| 63 |
+
"sans-serif",
|
| 64 |
+
),
|
| 65 |
+
font_mono: fonts.Font
|
| 66 |
+
| str
|
| 67 |
+
| Iterable[fonts.Font | str] = (
|
| 68 |
+
fonts.GoogleFont("IBM Plex Mono"),
|
| 69 |
+
"ui-monospace",
|
| 70 |
+
"monospace",
|
| 71 |
+
),
|
| 72 |
+
):
|
| 73 |
+
super().__init__(
|
| 74 |
+
primary_hue=primary_hue,
|
| 75 |
+
secondary_hue=secondary_hue,
|
| 76 |
+
neutral_hue=neutral_hue,
|
| 77 |
+
spacing_size=spacing_size,
|
| 78 |
+
radius_size=radius_size,
|
| 79 |
+
font=font,
|
| 80 |
+
font_mono=font_mono,
|
| 81 |
+
)
|
| 82 |
+
super().set(
|
| 83 |
+
button_primary_background_fill="linear-gradient(90deg, *primary_300, *secondary_400)",
|
| 84 |
+
button_primary_background_fill_hover="linear-gradient(90deg, *primary_200, *secondary_300)",
|
| 85 |
+
button_primary_text_color="white",
|
| 86 |
+
button_primary_background_fill_dark="linear-gradient(90deg, *primary_600, *secondary_800)",
|
| 87 |
+
block_shadow="*shadow_drop_lg",
|
| 88 |
+
button_shadow="*shadow_drop_lg",
|
| 89 |
+
input_background_fill="zinc",
|
| 90 |
+
input_border_color="*secondary_300",
|
| 91 |
+
input_shadow="*shadow_drop",
|
| 92 |
+
input_shadow_focus="*shadow_drop_lg",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
seafoam = SeafoamCustom()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
with gr.Blocks(theme=seafoam, analytics_enabled=False, css=css) as demo:
|
| 100 |
+
with gr.Column():
|
| 101 |
+
gr.Markdown(
|
| 102 |
+
""" ## Dolly 2.0
|
| 103 |
+
|
| 104 |
+
Dolly 2.0 is a 12B parameter language model based on the EleutherAI pythia model family and fine-tuned exclusively on a new, high-quality human generated instruction following dataset, crowdsourced among Databricks employees. For more details, please refer to the [model card](https://huggingface.co/databricks/dolly-v2-12b)
|
| 105 |
+
|
| 106 |
+
Type in the box below and click the button to generate answers to your most pressing questions!
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
)
|
| 110 |
+
gr.HTML("<p>You can duplicate this Space to run it privately without a queue for shorter queue times : <a style='display:inline-block' href='https://huggingface.co/spaces/RamAnanth1/Dolly-v2?duplicate=true'><img src='https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14' alt='Duplicate Space'></a> </p>")
|
| 111 |
+
|
| 112 |
+
with gr.Row():
|
| 113 |
+
with gr.Column(scale=3):
|
| 114 |
+
instruction = gr.Textbox(placeholder="Enter your question here", label="Question", elem_id="q-input")
|
| 115 |
+
|
| 116 |
+
with gr.Box():
|
| 117 |
+
gr.Markdown("**Answer**")
|
| 118 |
+
output = gr.Markdown(elem_id="q-output")
|
| 119 |
+
submit = gr.Button("Generate", variant="primary")
|
| 120 |
+
gr.Examples(
|
| 121 |
+
examples=examples,
|
| 122 |
+
inputs=[instruction],
|
| 123 |
+
cache_examples=False,
|
| 124 |
+
fn=process_example,
|
| 125 |
+
outputs=[output],
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
submit.click(generate, inputs=[instruction], outputs=[output])
|
| 131 |
+
instruction.submit(generate, inputs=[instruction], outputs=[output])
|
| 132 |
+
|
| 133 |
+
demo.queue(concurrency_count=16).launch(debug=True)
|
instruct_pipeline.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from transformers import Pipeline, PreTrainedTokenizer
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
INSTRUCTION_KEY = "### Instruction:"
|
| 10 |
+
RESPONSE_KEY = "### Response:"
|
| 11 |
+
END_KEY = "### End"
|
| 12 |
+
INTRO_BLURB = (
|
| 13 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request."
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# This is the prompt that is used for generating responses using an already trained model. It ends with the response
|
| 17 |
+
# key, where the job of the model is to provide the completion that follows it (i.e. the response itself).
|
| 18 |
+
PROMPT_FOR_GENERATION_FORMAT = """{intro}
|
| 19 |
+
{instruction_key}
|
| 20 |
+
{instruction}
|
| 21 |
+
{response_key}
|
| 22 |
+
""".format(
|
| 23 |
+
intro=INTRO_BLURB,
|
| 24 |
+
instruction_key=INSTRUCTION_KEY,
|
| 25 |
+
instruction="{instruction}",
|
| 26 |
+
response_key=RESPONSE_KEY,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_special_token_id(tokenizer: PreTrainedTokenizer, key: str) -> int:
|
| 31 |
+
"""Gets the token ID for a given string that has been added to the tokenizer as a special token.
|
| 32 |
+
When training, we configure the tokenizer so that the sequences like "### Instruction:" and "### End" are
|
| 33 |
+
treated specially and converted to a single, new token. This retrieves the token ID each of these keys map to.
|
| 34 |
+
Args:
|
| 35 |
+
tokenizer (PreTrainedTokenizer): the tokenizer
|
| 36 |
+
key (str): the key to convert to a single token
|
| 37 |
+
Raises:
|
| 38 |
+
RuntimeError: if more than one ID was generated
|
| 39 |
+
Returns:
|
| 40 |
+
int: the token ID for the given key
|
| 41 |
+
"""
|
| 42 |
+
token_ids = tokenizer.encode(key)
|
| 43 |
+
if len(token_ids) > 1:
|
| 44 |
+
raise ValueError(f"Expected only a single token for '{key}' but found {token_ids}")
|
| 45 |
+
return token_ids[0]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class InstructionTextGenerationPipeline(Pipeline):
|
| 49 |
+
def __init__(
|
| 50 |
+
self, *args, do_sample: bool = True, max_new_tokens: int = 256, top_p: float = 0.92, top_k: int = 0, **kwargs
|
| 51 |
+
):
|
| 52 |
+
super().__init__(*args, do_sample=do_sample, max_new_tokens=max_new_tokens, top_p=top_p, top_k=top_k, **kwargs)
|
| 53 |
+
|
| 54 |
+
def _sanitize_parameters(self, return_instruction_text=False, **generate_kwargs):
|
| 55 |
+
preprocess_params = {}
|
| 56 |
+
|
| 57 |
+
# newer versions of the tokenizer configure the response key as a special token. newer versions still may
|
| 58 |
+
# append a newline to yield a single token. find whatever token is configured for the response key.
|
| 59 |
+
tokenizer_response_key = next(
|
| 60 |
+
(token for token in self.tokenizer.additional_special_tokens if token.startswith(RESPONSE_KEY)), None
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
response_key_token_id = None
|
| 64 |
+
end_key_token_id = None
|
| 65 |
+
if tokenizer_response_key:
|
| 66 |
+
try:
|
| 67 |
+
response_key_token_id = get_special_token_id(self.tokenizer, tokenizer_response_key)
|
| 68 |
+
end_key_token_id = get_special_token_id(self.tokenizer, END_KEY)
|
| 69 |
+
|
| 70 |
+
# Ensure generation stops once it generates "### End"
|
| 71 |
+
generate_kwargs["eos_token_id"] = end_key_token_id
|
| 72 |
+
except ValueError:
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
forward_params = generate_kwargs
|
| 76 |
+
postprocess_params = {
|
| 77 |
+
"response_key_token_id": response_key_token_id,
|
| 78 |
+
"end_key_token_id": end_key_token_id,
|
| 79 |
+
"return_instruction_text": return_instruction_text,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
return preprocess_params, forward_params, postprocess_params
|
| 83 |
+
|
| 84 |
+
def preprocess(self, instruction_text, **generate_kwargs):
|
| 85 |
+
prompt_text = PROMPT_FOR_GENERATION_FORMAT.format(instruction=instruction_text)
|
| 86 |
+
inputs = self.tokenizer(
|
| 87 |
+
prompt_text,
|
| 88 |
+
return_tensors="pt",
|
| 89 |
+
)
|
| 90 |
+
inputs["prompt_text"] = prompt_text
|
| 91 |
+
inputs["instruction_text"] = instruction_text
|
| 92 |
+
return inputs
|
| 93 |
+
|
| 94 |
+
def _forward(self, model_inputs, **generate_kwargs):
|
| 95 |
+
input_ids = model_inputs["input_ids"]
|
| 96 |
+
attention_mask = model_inputs.get("attention_mask", None)
|
| 97 |
+
generated_sequence = self.model.generate(
|
| 98 |
+
input_ids=input_ids.to(self.model.device),
|
| 99 |
+
attention_mask=attention_mask,
|
| 100 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 101 |
+
**generate_kwargs,
|
| 102 |
+
)[0].cpu()
|
| 103 |
+
instruction_text = model_inputs.pop("instruction_text")
|
| 104 |
+
return {"generated_sequence": generated_sequence, "input_ids": input_ids, "instruction_text": instruction_text}
|
| 105 |
+
|
| 106 |
+
def postprocess(self, model_outputs, response_key_token_id, end_key_token_id, return_instruction_text):
|
| 107 |
+
sequence = model_outputs["generated_sequence"]
|
| 108 |
+
instruction_text = model_outputs["instruction_text"]
|
| 109 |
+
|
| 110 |
+
# The response will be set to this variable if we can identify it.
|
| 111 |
+
decoded = None
|
| 112 |
+
|
| 113 |
+
# If we have token IDs for the response and end, then we can find the tokens and only decode between them.
|
| 114 |
+
if response_key_token_id and end_key_token_id:
|
| 115 |
+
# Find where "### Response:" is first found in the generated tokens. Considering this is part of the
|
| 116 |
+
# prompt, we should definitely find it. We will return the tokens found after this token.
|
| 117 |
+
response_pos = None
|
| 118 |
+
response_positions = np.where(sequence == response_key_token_id)[0]
|
| 119 |
+
if len(response_positions) == 0:
|
| 120 |
+
logger.warn(f"Could not find response key {response_key_token_id} in: {sequence}")
|
| 121 |
+
else:
|
| 122 |
+
response_pos = response_positions[0]
|
| 123 |
+
|
| 124 |
+
if response_pos:
|
| 125 |
+
# Next find where "### End" is located. The model has been trained to end its responses with this
|
| 126 |
+
# sequence (or actually, the token ID it maps to, since it is a special token). We may not find
|
| 127 |
+
# this token, as the response could be truncated. If we don't find it then just return everything
|
| 128 |
+
# to the end. Note that even though we set eos_token_id, we still see the this token at the end.
|
| 129 |
+
end_pos = None
|
| 130 |
+
end_positions = np.where(sequence == end_key_token_id)[0]
|
| 131 |
+
if len(end_positions) > 0:
|
| 132 |
+
end_pos = end_positions[0]
|
| 133 |
+
|
| 134 |
+
decoded = self.tokenizer.decode(sequence[response_pos + 1 : end_pos]).strip()
|
| 135 |
+
else:
|
| 136 |
+
# Otherwise we'll decode everything and use a regex to find the response and end.
|
| 137 |
+
|
| 138 |
+
fully_decoded = self.tokenizer.decode(sequence)
|
| 139 |
+
|
| 140 |
+
# The response appears after "### Response:". The model has been trained to append "### End" at the
|
| 141 |
+
# end.
|
| 142 |
+
m = re.search(r"#+\s*Response:\s*(.+?)#+\s*End", fully_decoded, flags=re.DOTALL)
|
| 143 |
+
|
| 144 |
+
if m:
|
| 145 |
+
decoded = m.group(1).strip()
|
| 146 |
+
else:
|
| 147 |
+
# The model might not generate the "### End" sequence before reaching the max tokens. In this case,
|
| 148 |
+
# return everything after "### Response:".
|
| 149 |
+
m = re.search(r"#+\s*Response:\s*(.+)", fully_decoded, flags=re.DOTALL)
|
| 150 |
+
if m:
|
| 151 |
+
decoded = m.group(1).strip()
|
| 152 |
+
else:
|
| 153 |
+
logger.warn(f"Failed to find response in:\n{fully_decoded}")
|
| 154 |
+
|
| 155 |
+
if return_instruction_text:
|
| 156 |
+
return {"instruction_text": instruction_text, "generated_text": decoded}
|
| 157 |
+
|
| 158 |
+
return decoded
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.12.0
|
| 2 |
+
transformers[torch]==4.25.1
|
| 3 |
+
bitsandbytes
|