id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
153,277 | import jsonlines
import argparse
import json
import os
import spacy
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst | null |
153,278 | import jsonlines
import argparse
import json
import os
import spacy
def save_file_jsonl(data, fp):
with jsonlines.open(fp, mode='w') as writer:
writer.write_all(data) | null |
153,279 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
rel_tokens_names = ["[Irrelevant]", "[Relevant]"]
retrieval_tokens_names = ["[No Retrieval]", "[Retrieval]"]
ground_tokens_names = ["[Utility:1]", "[Utility:2]",
"[Utility:3]", "[Utility:4]", "[Utility:5]"]
utility_tokens_names = ["[Fully supported]",
"[Partially supported]", "[No support / Contradictory]"]
other_special_tokens = ["<s>", "</s>", "[PAD]",
"<unk>", "<paragraph>", "</paragraph>"]
def postprocess(pred):
special_tokens = rel_tokens_names + retrieval_tokens_names + \
ground_tokens_names + utility_tokens_names + other_special_tokens
for item in special_tokens:
pred = pred.replace(item, "")
pred = pred.replace("</s>", "")
pred = pred.replace("<unk>", "")
if len(pred) == 0:
return ""
if pred[0] == " ":
pred = pred[1:]
pred = pred.replace(" ", " ")
if len(pred) == 0:
return ""
if pred[-1] == " ":
pred = pred[:-1]
return pred | null |
153,280 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def save_file_jsonl(data, fp):
with jsonlines.open(fp, mode='w') as writer:
writer.write_all(data) | null |
153,281 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def load_json(fn):
return json.load(open(fn)) | null |
153,282 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
nlp = spacy.load("en_core_web_sm")
def split_sentences(paragraph):
doc = nlp(paragraph)
sentences = []
for sent in doc.sents:
sentences.append(sent.text)
return sentences | null |
153,283 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def convert_score_to_utility_token(pred):
if len(pred) == 0:
print("Utility empty")
return None
if "1" in pred or "2" in pred or "3" in pred or "4" in pred or "5" in pred:
for i in ["1", "2", "3", "4", "5"]:
if i in pred:
return "[Utility:{}]".format(i)
return "[Utility:{}]".format(5)
if pred in ["1", "2", "3", "4", "5", 1, 2, 3, 4, 5]:
return "[Utility:{}]".format(pred)
else:
if pred[0] != "[":
pred = "[" + pred
if pred in ["[Utility:1]", "[Utility:2]", "[Utility:3]", "[Utility:4]", "[Utility:5]"]:
return pred
else:
print(pred)
return None | null |
153,284 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def convert_score_to_retrieval_token(pred):
if len(pred) == 0:
print("Retrieve token empty")
return None
if pred[0] != "[":
pred = "[" + pred
if pred in ["[Retrieval]", "[No Retrieval]", "[Continue to Use Evidence]"]:
return pred
elif pred == "Yes" or pred == "[Yes]":
return "[Retrieval]"
elif pred == "No" or pred == "[No]":
return "[No Retrieval]"
else:
print(pred)
# print("not implemented")
return "[No Retrieval]" | null |
153,285 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def convert_score_to_groudness(pred):
if len(pred) == 0:
return None
if pred[0] != "[":
pred = "[" + pred
if pred in ["[No support / Contradictory]", "[Partially supported]", "[Fully supported]"]:
return pred
elif pred in ["4", "5"]:
return "[Fully supported]"
else:
print("invalid groundness")
print(pred)
return None | null |
153,286 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def combine_results(input_data, results, type):
for item, pred in zip(input_data, results["preds"]):
item[type] = pred
return input_data | null |
153,287 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def postprocess_relevance_reward_token(pred):
if len(pred) == 0:
print("relevance token empty")
return None
if "Relevant" in pred:
return "[Relevant]"
elif "Irrelevant" in pred:
return "[Irrelevant]"
else:
return None | null |
153,288 | import json
from collections import Counter
import random
import jsonlines
import argparse
from pathlib import Path
import spacy
import os
from transformers import AutoTokenizer
from tqdm import tqdm
import numpy as np
def load_file(file_name):
print(file_name)
if file_name.endswith(".json"):
data = json.load(open(file_name))
elif file_name.endswith(".jsonl"):
data = load_jsonlines(file_name)
else:
if ".json_" in file_name:
data = json.load(open(file_name))
elif ".jsonl_" in file_name:
data = load_jsonlines(file_name)
return data
def load_all_files(file_paths):
final_results = {}
for fp in file_paths:
data = load_file(fp)
for item in data:
q_id = item["id"] if "id" in item else item["q_id"]
final_results.setdefault(q_id, [])
final_results[q_id].append(item)
return final_results | null |
153,289 | from tqdm import tqdm
import jsonlines
import argparse
import json
import os
import spacy
nlp = spacy.load("en_core_web_sm")
def split_sentences(paragraph):
doc = nlp(paragraph)
sentences = []
for sent in doc.sents:
sentences.append(sent.text)
return sentences | null |
153,290 | from tqdm import tqdm
import jsonlines
import argparse
import json
import os
import spacy
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst | null |
153,291 | from tqdm import tqdm
import jsonlines
import argparse
import json
import os
import spacy
def save_file_jsonl(data, fp):
with jsonlines.open(fp, mode='w') as writer:
writer.write_all(data) | null |
153,292 | import random
import torch
import os
import numpy as np
import copy
from tqdm import tqdm
import json
import argparse
from tqdm import tqdm
import jsonlines
from vllm import LLM, SamplingParams
def posprocess_output(answer, return_score=False):
answer = answer.replace("</s>", "")
answer = answer.replace("<unk>", "")
answer = answer.replace("[PAD]", "")
return answer
def call_model(prompts, model, max_new_tokens=50):
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, max_tokens=max_new_tokens)
preds = model.generate(prompts, sampling_params)
preds = [pred.outputs[0].text.split("\n\n")[0] for pred in preds]
postprocessed_preds = [posprocess_output(pred) for pred in preds]
return postprocessed_preds, preds | null |
153,293 | import random
import torch
import os
import numpy as np
import copy
from tqdm import tqdm
import json
import argparse
from tqdm import tqdm
import jsonlines
from vllm import LLM, SamplingParams
def accuracy(prediction, ground_truth):
for gt in ground_truth:
if prediction == gt:
return 1
else:
return 0 | null |
153,294 | import random
import torch
import os
import numpy as np
import copy
from tqdm import tqdm
import json
import argparse
from tqdm import tqdm
import jsonlines
from vllm import LLM, SamplingParams
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst | null |
153,295 | import random
import torch
import os
import numpy as np
import copy
from tqdm import tqdm
import json
import argparse
from tqdm import tqdm
import jsonlines
from vllm import LLM, SamplingParams
ALPACA_PROMPT_DICT = {
"prompt_input": (
"Below is an instruction that describes a task, paired with an input that provides further context. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
),
"prompt_no_input": (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Response:"
),
}
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def process_data(input_data, inst_mode, input_mode, split="train", multi_retrieval=False):
if split == "train":
prompt = ALPACA_PROMPT_DICT["prompt_input"].format_map(input_data)
output = str(input_data["output"])
return prompt, output
else:
instruction = PROMPT_DICT[inst_mode]
if multi_retrieval is True and (input_data["sent_idx"] == 0 or "preceding_sentences" not in input_data or type(input_data["preceding_sentences"]) is not str or len(input_data["preceding_sentences"]) == 0):
input = PROMPT_DICT[input_mode +
"_no_preceding"].format_map(input_data)
else:
input = PROMPT_DICT[input_mode].format_map(input_data)
prompt = ALPACA_PROMPT_DICT["prompt_input"].format_map(
{"instruction": instruction, "input": input})
output = "None"
return prompt, output | null |
153,296 | import random
import torch
import os
import numpy as np
import copy
from tqdm import tqdm
import json
import argparse
from tqdm import tqdm
import jsonlines
from vllm import LLM, SamplingParams
ALPACA_PROMPT_DICT = {
"prompt_input": (
"Below is an instruction that describes a task, paired with an input that provides further context. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
),
"prompt_no_input": (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Response:"
),
}
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def process_data(input_data, inst_mode, input_mode, split="train", multi_retrieval=False):
if split == "train":
prompt = ALPACA_PROMPT_DICT["prompt_input"].format_map(input_data)
# instruction = PROMPT_DICT[inst_mode]
# input = PROMPT_DICT[input_mode].format_map(input_data)
# prompt = ALPACA_PROMPT_DICT["prompt_input"].format_map({"instruction": instruction, "input": input})
output = str(input_data["output"])
return prompt, output
else:
instruction = PROMPT_DICT[inst_mode]
if multi_retrieval is True and (input_data["sent_idx"] == 0 or "preceding_sentences" not in input_data or type(input_data["preceding_sentences"]) is not str or len(input_data["preceding_sentences"]) == 0):
input = PROMPT_DICT[input_mode +
"_no_preceding"].format_map(input_data)
else:
input = PROMPT_DICT[input_mode].format_map(input_data)
prompt = ALPACA_PROMPT_DICT["prompt_input"].format_map(
{"instruction": instruction, "input": input})
output = "None"
return prompt, output | null |
153,297 | import json
import jsonlines
import argparse
import random
from collections import Counter
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def create_utility_data(input_data):
print("creating retrieval data")
processed_data = []
for item in input_data:
input = item["input"]
raw_output = item["raw_output"]
if item["score"] == "":
item["score"] = raw_output.split("\n")[0]
output = item["score"]
if output not in [1,2,3,4,5] or len(str(output)) == 0:
continue
label = "[Utility:{}]".format(output)
processed_data.append({"instruction": PROMPT_DICT["utility_instruction"], "input": PROMPT_DICT["utility_input"].format_map(input), "output": label, "task": "utility"})
print(processed_data[-1])
print("total data number: {}".format(len(processed_data)))
print(Counter([item["output"] for item in processed_data ]))
return processed_data | null |
153,298 | import json
import jsonlines
import argparse
import random
from collections import Counter
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def create_retrieval_data(input_data, multi_retrieval=False):
print("creating multi sentence retrieval data")
processed_data = []
for item in input_data:
input = item["input"]
output = item["decision_token"]
if len(str(output)) == 0:
continue
if output not in [ "[Retrieval]", "[No Retrieval]", "[Continue to Use Evidence]"]:
continue
if "sent_idx" not in item or item["sent_idx"] == 0 or len(item["preceding_sentences"]) == 0:
processed_data.append({"instruction": PROMPT_DICT["multi_retrieval_three_way_instruction"], "input": PROMPT_DICT["multi_retrieval_three_way_input_wo_preceding"].format_map(input), "output": output, "task": "multi_retrieval"})
else:
processed_data.append({"instruction": PROMPT_DICT["multi_retrieval_three_way_instruction"], "input": PROMPT_DICT["multi_retrieval_three_way_input"].format_map(input), "output": output, "task": "retrieval"})
print(processed_data[-1])
print("total data number: {}".format(len(processed_data)))
print(Counter([item["output"] for item in processed_data ]))
return processed_data | null |
153,299 | import json
import jsonlines
import argparse
import random
from collections import Counter
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def create_retrieval_data_input_only(input_data):
print("creating retrieval data")
processed_data = []
for item in input_data:
input = {"instruction": item["input"].split("##\nTask instruction: ")[1]}
output = item["output"]
if len(str(output)) == 0:
continue
if "Yes" in output:
output = "[Retrieval]"
elif "No" in output:
output = "[No Retrieval]"
else:
continue
assert output in [ "[Retrieval]", "[No Retrieval]" ]
processed_data.append({"instruction": PROMPT_DICT["retrieval_instruction"], "input": PROMPT_DICT["retrieval_input"].format_map(input), "output": output, "task": "retrieval"})
print(processed_data[-1])
print("total data number: {}".format(len(processed_data)))
print(Counter([item["output"] for item in processed_data ]))
return processed_data | null |
153,300 | import json
import jsonlines
import argparse
import random
from collections import Counter
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def create_groundness_data(input_data, multi_retrieval=False):
print("creating groundness data")
processed_data = []
for item in input_data:
input = item["input"]
raw_output = item["raw_output"]
if item["score"] == "":
item["score"] = raw_output.split("\n")[0]
if len(item["score"]) > 0 and item["score"][-1] == " ":
item["score"] = item["score"][:-1]
if len(item["score"]) == 0 or item["score"] not in ["[No support / Contradictory]", "[Fully supported]", "[Partially supported]"]:
continue
if multi_retrieval is True:
if "sent_idx" not in item or item["sent_idx"] == 0 or len(item["preceding_sentences"]) == 0:
processed_data.append({"instruction": PROMPT_DICT["ground_multi_instruction"], "input": PROMPT_DICT["ground_multi_input_wo_preceding"].format_map(input), "output": item["score"], "task": "groudness"})
else:
processed_data.append({"instruction": PROMPT_DICT["ground_multi_instruction"], "input": PROMPT_DICT["ground_multi_input"].format_map(input), "output": item["score"], "task": "groudness"})
else:
processed_data.append({"instruction": PROMPT_DICT["ground_instruction"], "input": PROMPT_DICT["ground_input"].format_map(input), "output": item["score"], "task": "groudness"})
print(processed_data[-1])
print("total data number: {}".format(len(processed_data)))
print(Counter([item["output"] for item in processed_data ]))
return processed_data | null |
153,301 | import json
import jsonlines
import argparse
import random
from collections import Counter
PROMPT_DICT = {
"ground_instruction": (
"You will be given an task instruction, evidence, and output. Your objective is to assess the extent to which the output is supported by the information presented in the evidence.\n"
"Rate the level of support on a scale from 1 ( Ignore / Contradictory), 2 (Little support), 3 (Partially supported), 4 (Mostly supported), 5 (Fully supported)."
),
"ground_input": (
"##\nTask instruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {output}"
),
"ground_multi_instruction": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
),
"ground_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"ground_multi_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}"
),
"retrieval_instruction": (
"When provided with instruction, please evaluate whether seeking additional information from external sources such as the web (e.g., Wikipedia) aids in producing a more comprehensive response. Respond with either [Retrieval] or [No Retrieval]."
),
"retrieval_input": (
"Task instruction: {instruction}"
),
"retrieval_multi_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
),
"retrieval_multi_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_instruction": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
),
"multi_retrieval_three_way_input": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"multi_retrieval_three_way_input_wo_preceding": (
"Task instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}"
),
"relevance_instruction": (
"When given instruction and evidence, evaluate whether the evidence is relevant to the instruction and provides valuable information for generating meaningful responses.\n"
"Use a rating of [Relevant] to indicate relevance and usefulness, and [Irrelevant] to indicate irrelevance."
),
"relevance_input": (
"Task instruction: {instruction}\n"
"Evidence: {evidence}"
),
"utility_instruction": (
"Given an instruction and an output, rate whether the response appears to be a helpful and informative answer to the query, from 1 (lowest) - 5 (highest). We call this score perceived utility.\n"
"[Utility:5]: The response provides a complete, highly detailed, and informative response to the query, fully satisfying the information needs.\n"
"[Utility:4]: The response mostly fulfills the need in the query, while there can be some minor improvements such as discussing more detailed information, having better structure of the response, or improving coherence. \n"
"[Utility:3]: The response is acceptable, but some major additions or improvements are needed to satisfy users' needs.\n"
"[Utility:2]: The response still addresses the main request, but it is not complete or not relevant to the query.\n"
"[Utility:1]: The response is barely on-topic or completely irrelevant.\n"
),
"utility_input": (
"Task instruction: {instruction}\n"
"Output: {output}"
),
}
def create_relevance_data(input_data):
print("creating relevance data")
processed_data = []
for item in input_data:
input = item["input"]
raw_output = item["raw_output"]
if item["score"] == "":
item["score"] = raw_output.split("\n")[0]
if len(item["score"]) > 0 and item["score"][-1] == " ":
item["score"] = item["score"][:-1]
if item["score"] not in ["[Relevant]", "[Irrelevant]"]:
continue
label = item["score"]
if label == "[Relevant]" and random.random() > 0.7:
continue
processed_data.append({"instruction": PROMPT_DICT["relevance_instruction"], "input": PROMPT_DICT["relevance_input"].format_map(input), "output": label, "task": "relevance"})
print(processed_data[-1])
print("total data number: {}".format(len(processed_data)))
print(Counter([item["output"] for item in processed_data ]))
return processed_data | null |
153,302 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
def completions_with_backoff(**kwargs):
return openai.ChatCompletion.create(**kwargs) | null |
153,303 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst | null |
153,304 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
def postprocess(results):
raw_output = results["choices"][0]["message"]["content"]
if "\nExplanation:" in raw_output:
explanation = raw_output.split("\nExplanation:")[1]
if explanation[0] == " ":
explanation = explanation[1:]
decision_token = raw_output.split("\nExplanation:")[0]
if decision_token is None:
return "", explanation
else:
return decision_token, explanation
else:
return "", "" | null |
153,305 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
PROMPT_DICT = {
"context": (
"Given an instruction, please make a judgment on whether finding some external documents from the web (e.g., Wikipedia) helps to generate a better response. Please answer [Yes] or [No] and write an explanation.\n\n"
"##\nInstruction: Give three tips for staying healthy.\n"
"Need retrieval?: [Yes]\n"
"Explanation: There might be some online sources listing three tips for staying healthy or some reliable sources to explain the effects of different behaviors on health. So retrieving documents is helpful to improve the response to this query.\n\n"
"##\nInstruction: Describe a time when you had to make a difficult decision.\n"
"Need retrieval?: [No]\n"
"Explanation: This instruction is asking about some personal experience and thus it does not require one to find some external documents.\n\n"
"##\nInstruction: Write a short story in third person narration about a protagonist who has to make an important career decision.\n"
"Need retrieval?: [No]\n"
"Explanation: This instruction asks us to write a short story, which does not require external evidence to verify.\n\n"
"##\nInstruction: What is the capital of France?\n"
"Need retrieval?: [Yes]\n"
"Explanation: While the instruction simply asks us to answer the capital of France, which is a widely known fact, retrieving web documents for this question can still help.\n\n"
"##\n Instruction: Find the area of a circle given its radius. Radius = 4\n"
"Need retrieval?: [No]\n"
"Explanation: This is a math question and although we may be able to find some documents describing a formula, it is unlikely to find a document exactly mentioning the answer.\n\n"
"##\nInstruction: Arrange the words in the given sentence to form a grammatically correct sentence. quickly the brown fox jumped\n"
"Need retrieval?: [No]\n"
"Explanation: This task doesn't require any external evidence, as it is a simple grammatical question.\n\n"
"##\nInstruction: Explain the process of cellular respiration in plants."
"Need retrieval?: [Yes]\n"
"Explanation: This instruction asks for a detailed description of a scientific concept, and is highly likely that we can find a reliable and useful document to support the response.\n\n"
"##\nInstruction:{instruction}\n"
"Need retrieval?: "
),
"multi_retrieval": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
"##\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured.\n"
"Evidence: Word embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension.\n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Rating: [Retrieval]\n"
"Explanation: The output discusses the applications of word embeddings, while the evidence only discusses the definitions of word embeddings and how it works. Therefore, we need to retrieve other evidence to verify whether the output is actually correct or not.\n"
"###\nInstruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}\n"
"Rating: "),
"multi_retrieval_no_preceding": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. If the output sentence can be verified solely with the evidence or doesn’t require any verification, respond with [No Retrieval]. If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments.\n\n"
"##\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured.\n"
"Evidence: Word embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension.\n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Rating: [Retrieval]\n"
"Explanation: The output discusses the applications of word embeddings, while the evidence only discusses the definitions of word embeddings and how it works. Therefore, we need to retrieve other evidence to verify whether the output is actually correct or not.\n"
"###\nInstruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {target_output}\n"
"Rating: "
),
"multi_retrieval_three_way": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
"##\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured. \n"
"Evidence:\nWord embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension. \n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Rating: [Retrieval]\n"
"Explanation: The output discusses the applications of word embeddings, while the evidence only discusses the definitions of word embeddings and how it works. Therefore, we need to retrieve other evidence to verify whether the output is correct or not.\n"
"###\nInstruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Evidence: {evidence}\n"
"Output: {target_output}\n"
"Rating: "
),
"multi_retrieval_three_way_no_preceding": (
"You will be provided with an instruction, evidence, output sentence, and preceding sentences (optional). If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to determine whether the information in the output sentence can be fully verified by the evidence or if it requires further external verification. There are three cases:\n"
"- If the output sentence can be verified solely with the evidence, then respond with [Continue to Use Evidence]. \n"
"- If the sentence doesn't require any factual verification (e.g., a subjective sentence or a sentence about common sense), then respond with [No Retrieval]. \n"
"- If additional information is needed to verify the output sentence, respond with [Retrieval]. Please provide explanations for your judgments. \n\n"
"##\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured. \n"
"Evidence:\nWord embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension. \n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Rating: [Retrieval]\n"
"Explanation: The output discusses the applications of word embeddings, while the evidence only discusses the definitions of word embeddings and how it works. Therefore, we need to retrieve other evidence to verify whether the output is correct or not.\n"
"###\nInstruction: {instruction}\n"
"Evidence: {evidence}\n"
"Output: {target_output}\n"
"Rating: "
)
}
def process_input(example, multi_retrieval=False, three_way=False):
if multi_retrieval is False:
return PROMPT_DICT["context"].format_map(example)
else:
if example["sent_idx"] == 0 or len(example["preceding_sentences"]) == 0:
if three_way is False:
return PROMPT_DICT["multi_retrieval_no_preceding"].format_map(example)
else:
return PROMPT_DICT["multi_retrieval_three_way"].format_map(example)
else:
if three_way is False:
return PROMPT_DICT["multi_retrieval"].format_map(example)
else:
return PROMPT_DICT["multi_retrieval_three_way_no_preceding"].format_map(example) | null |
153,306 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
from sacrebleu.metrics import BLEU, CHRF, TER
def completions_with_backoff(**kwargs):
return openai.ChatCompletion.create(**kwargs) | null |
153,307 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
from sacrebleu.metrics import BLEU, CHRF, TER
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst | null |
153,308 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
from sacrebleu.metrics import BLEU, CHRF, TER
def postprocess(results):
raw_output = results["choices"][0]["message"]["content"]
return raw_output | null |
153,311 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
def postprocess(results):
raw_output = results["choices"][0]["message"]["content"]
print(raw_output)
if "\nExplanation:" in raw_output:
explanation = raw_output.split("\nExplanation:")[1]
if explanation[0] == " ":
explanation = explanation[1:]
score_string = raw_output.split("\nExplanation:")[0]
score = None
for i in range(1, 6):
if str(i) in score_string:
score = int(i)
if score is None:
return "", explanation
else:
return score, explanation
else:
return "", "" | null |
153,312 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
PROMPT_DICT = {
"multi": (
"You'll be provided with an instruction, along with evidence and possibly some preceding sentences. "
"When there are preceding sentences, your focus should be on the sentence that comes after them. "
"Your job is to determine if the evidence is relevant to the initial instruction and the preceding context, and provides useful information to complete the task described in the instruction. "
"If the evidence meets this requirement, respond with [Relevant]; otherwise, generate [Irrelevant].\n\n"
"###\nInstruction: Given four answer options, A, B, C, and D, choose the best answer.\n\n"
"Input: Earth rotating causes\n"
"A: the cycling of AM and PM\nB: the creation of volcanic eruptions\nC: the cycling of the tides\nD: the creation of gravity\n\n"
"Evidence: Rotation causes the day-night cycle which also creates a corresponding cycle of temperature and humidity creates a corresponding cycle of temperature and humidity. Sea level rises and falls twice a day as the earth rotates.\n\n"
"Rating: [Relevant]\n"
"Explanation: The evidence explicitly mentions that the rotation causes a day-night cycle, as described in the answer option A.\n\n"
"###\nInstruction: age to run for us house of representatives\n\n"
"Evidence: The Constitution sets three qualifications for service in the U.S. Senate: age (at least thirty years of age); U.S. citizenship (at least nine years); and residency in the state a senator represents at the time of election.\n\n"
"Rating: [Irrelevant]\n"
"Explanation: The evidence only discusses the ages to run for the US Senate, not for the House of Representatives.\n\n"
"###\nInstruction: {instruction}\n\n"
"Evidence: {evidence}\n\n"
"Rating:"
),
"multi_no_preceding": (
"You'll be provided with an instruction, along with evidence and possibly some preceding sentences. "
"When there are preceding sentences, your focus should be on the sentence that comes after them. "
"Your job is to determine if the evidence is relevant to the initial instruction and the preceding context, and provides useful information to complete the task described in the instruction. "
"If the evidence meets this requirement, respond with [Relevant]; otherwise, generate [Irrelevant].\n\n"
"###\nInstruction: Given four answer options, A, B, C, and D, choose the best answer.\n\n"
"Input: Earth rotating causes\n"
"A: the cycling of AM and PM\nB: the creation of volcanic eruptions\nC: the cycling of the tides\nD: the creation of gravity\n\n"
"Evidence: Rotation causes the day-night cycle which also creates a corresponding cycle of temperature and humidity creates a corresponding cycle of temperature and humidity. Sea level rises and falls twice a day as the earth rotates.\n\n"
"Rating: [Relevant]\n"
"Explanation: The evidence explicitly mentions that the rotation causes a day-night cycle, as described in the answer option A.\n\n"
"###\nInstruction: Describe a leader or a politician whom you admire. \n\n"
"Preceding sentences: Leaders and politicians have the power to shape the course of history and impact the lives of countless individuals. Among the myriad of notable figures, Nelson Mandela stands as an exemplary leader whose indomitable spirit, unwavering commitment to justice, and remarkable ability to unite a divided nation have made him an admired and revered personality on a global scale. "
"Evidence: Barack Obama was one of the most influential people of the world and the man with a difference. He has served as the President of the United States of America. He was the 44th President of America. He was elected in the year 2009 to the office of the President. He was the first-ever African-American President of America.\n\n"
"Rating: [Irrelevant]\n"
"Explanation: While the evidence discuss Barack Obama, who is known as an influential political leader, the preceding sentences describe Nelson Mandela, so this evidence doesn't provide useful information to generate an helpful continuation.\n\n"
"###\nInstruction: {instruction}\n\n"
"Evidence: {evidence}\n\n"
"Rating:"
),
}
def process_input(example, multi_retrieval=False):
if multi_retrieval is False:
return PROMPT_DICT["context"].format_map(example)
else:
if "sent_idx" not in example or example["sent_idx"] == 0 or len(example["preceding_sentences"]) == 0:
return PROMPT_DICT["multi_no_preceding"].format_map(example)
else:
return PROMPT_DICT["multi"].format_map(example) | null |
153,315 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
def postprocess(results):
raw_output = results["choices"][0]["message"]["content"]
if "\nExplanation:" in raw_output:
explanation = raw_output.split("\nExplanation:")[1]
score_string = raw_output.split("\nExplanation:")[0]
score = None
for i in range(1, 6):
if str(i) in score_string:
score = int(i)
if score is None:
return "", explanation
else:
return score, explanation
else:
return "", "" | null |
153,319 | import openai
import pandas as pd
import argparse
import json
from collections import Counter
from tqdm import tqdm
import backoff
from openai.error import APIError, Timeout, APIConnectionError
import jsonlines
import random
PROMPT_DICT = {
"context": (
"You will receive an instruction, evidence, and output.\n"
"Your task is to evaluate if the output is fully supported by the information provided in the evidence.\n"
"Use the following entailment scale to generate a score:\n"
"5: Fully supported - All information in output is supported by the evidence, or extractions from the evidence. This is a somewhat extreme case and is only applicable when the output and part of the evidence are almost identical.\n"
"4: Mostly supported - Most of the information in the output is supported by the evidence, but there is some minor information that is not supported. In other words, if an output is a paraphrase of the evidence or a less concrete version of the descriptions of the evidence, it should be considered a 4.\n"
"3: Partially supported - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a 3. If the output covers a lot of new information that is not discussed in the evidence, it should be 3.\n"
"2: Little support - The output and evidence are only loosely related, and most of the information in the output isn't supported by the evidence.\n"
"1: Ignore / Contradictory - The output completely ignores evidence or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not.\n"
"Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
"###\nInstruction: Explain the use of word embeddings in Natural Language Processing\n\n"
"Output: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured. Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies. They allow for words to be processed as numerical values, giving machines an easier way to perform NLP tasks.\n\n"
"Evidence: Word embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension. Methods to generate this mapping include neural networks, dimensionality reduction on the word co-occurrence matrix, probabilistic models, explainable knowledge base method, and explicit representation in terms of the context in which words appear. Word and phrase embeddings, when used as the underlying input representation, have been shown to boost the performance in NLP tasks such as syntactic parsing and sentiment analysis.\n\n"
"Score: 4\n"
"Explanation: Although the wording isn't exactly same, the evidence verifies all of the claims in the output such as definitions and the use cases in NLP. Therefore, it should be rated as 4.\n\n"
"###\nInstruction: {instruction}\n\n"
"Output: {output}\n\n"
"Evidence: {evidence}\n\n"
"Score:"
),
"multi": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
"###\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured.\n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Evidence: Word embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Word and phrase embeddings, when used as the underlying input representation, have been shown to boost the performance in NLP tasks such as syntactic parsing, sentiment analysis, next token predictions as well as analogy detection.\n"
"Score: [Fully supported]\n"
"Explanation: The output sentence discusses the application of word embeddings, and the evidence mentions all of the applications syntactic parsing, sentiment analysis, next token predictions as well as analogy detection as the applications. Therefore, the score should be [Fully supported].\n\n"
"###\n"
"Instruction: {instruction}\n"
"Preceding sentences: {preceding_sentences}\n"
"Output: {target_output}\n"
"Evidence: {evidence}\n"
"Score: "
),
"multi_no_preceding": (
"You will receive an instruction, evidence, and output, and optional preceding sentences. If the preceding sentence is given, the output should be the sentence that follows those preceding sentences. Your task is to evaluate if the output is fully supported by the information provided in the evidence, and provide explanations on your judgement.\n"
"Use the following entailment scale to generate a score:\n"
"[Fully supported] - All information in output is supported by the evidence, or extractions from the evidence. This is only applicable when the output and part of the evidence are almost identical.\n"
"[Partially supported] - The output is supported by the evidence to some extent, but there is major information in the output that is not discussed in the evidence. For example, if an instruction asks about two concepts and the evidence only discusses either of them, it should be considered a [Partially supported].\n"
"[No support / Contradictory] - The output completely ignores evidence, is unrelated to the evidence, or contradicts the evidence. This can also happen if the evidence is irrelevant to the instruction.\n\n"
"Make sure to not use any external information/knowledge to judge whether the output is true or not. Only check whether the output is supported by the evidence, and not whether the output follows the instructions or not.\n\n"
"###\nInstruction: Explain the use of word embeddings in Natural Language Processing.\n"
"Preceding sentences: Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured.\n"
"Output: Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies.\n"
"Evidence: Word embedding\nWord embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Word and phrase embeddings, when used as the underlying input representation, have been shown to boost the performance in NLP tasks such as syntactic parsing, sentiment analysis, next token predictions as well as analogy detection.\n"
"Score: [Fully supported]\n"
"Explanation: The output sentence discusses the application of word embeddings, and the evidence mentions all of the applications syntactic parsing, sentiment analysis, next token predictions as well as analogy detection as the applications. Therefore, the score should be [Fully supported].\n\n"
"###\n"
"Instruction: {instruction}\n"
"Output: {target_output}\n"
"Evidence: {evidence}\n"
"Score: "
)
}
def process_input(example, multi_retrieval=False):
if multi_retrieval is False:
return PROMPT_DICT["context"].format_map(example)
else:
if "sent_idx" not in example or example["sent_idx"] == 0 or len(example["preceding_sentences"]) == 0:
return PROMPT_DICT["multi_no_preceding"].format_map(example)
else:
return PROMPT_DICT["multi"].format_map(example) | null |
153,320 | import copy
import logging
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import torch
import transformers
from torch.utils.data import Dataset
from transformers import Trainer
import json
import io
import os
from ..retrieval_lm.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
def _make_w_io_base(f, mode: str):
if not isinstance(f, io.IOBase):
f_dirname = os.path.dirname(f)
if f_dirname != "":
os.makedirs(f_dirname, exist_ok=True)
f = open(f, mode=mode)
return f
The provided code snippet includes necessary dependencies for implementing the `jdump` function. Write a Python function `def jdump(obj, f, mode="w", indent=4, default=str)` to solve the following problem:
Dump a str or dictionary to a file in json format. Args: obj: An object to be written. f: A string path to the location on disk. mode: Mode for opening the file. indent: Indent for storing json dictionaries. default: A function to handle non-serializable entries; defaults to `str`.
Here is the function:
def jdump(obj, f, mode="w", indent=4, default=str):
"""Dump a str or dictionary to a file in json format.
Args:
obj: An object to be written.
f: A string path to the location on disk.
mode: Mode for opening the file.
indent: Indent for storing json dictionaries.
default: A function to handle non-serializable entries; defaults to `str`.
"""
f = _make_w_io_base(f, mode)
if isinstance(obj, (dict, list)):
json.dump(obj, f, indent=indent, default=default)
elif isinstance(obj, str):
f.write(obj)
else:
raise ValueError(f"Unexpected type: {type(obj)}")
f.close() | Dump a str or dictionary to a file in json format. Args: obj: An object to be written. f: A string path to the location on disk. mode: Mode for opening the file. indent: Indent for storing json dictionaries. default: A function to handle non-serializable entries; defaults to `str`. |
153,321 | import copy
import logging
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import torch
import transformers
from torch.utils.data import Dataset
from transformers import Trainer
import json
import io
import os
from ..retrieval_lm.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
def _make_r_io_base(f, mode: str):
if not isinstance(f, io.IOBase):
f = open(f, mode=mode)
return f
The provided code snippet includes necessary dependencies for implementing the `jload` function. Write a Python function `def jload(f, mode="r")` to solve the following problem:
Load a .json file into a dictionary.
Here is the function:
def jload(f, mode="r"):
"""Load a .json file into a dictionary."""
f = _make_r_io_base(f, mode)
jdict = json.load(f)
f.close()
return jdict | Load a .json file into a dictionary. |
153,322 | import copy
import logging
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import torch
import transformers
from torch.utils.data import Dataset
from transformers import Trainer
import json
import io
import os
from ..retrieval_lm.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
IGNORE_INDEX = -100
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
"""Tokenize a list of strings."""
tokenized_list = [
tokenizer(
text,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
)
for text in strings
]
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
input_ids_lens = labels_lens = [
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
]
return dict(
input_ids=input_ids,
labels=labels,
input_ids_lens=input_ids_lens,
labels_lens=labels_lens,
)
The provided code snippet includes necessary dependencies for implementing the `preprocess` function. Write a Python function `def preprocess( sources: Sequence[str], targets: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, skip_tokens:Sequence[int], context_markups: Sequence[int], ) -> Dict` to solve the following problem:
Preprocess the data by tokenizing.
Here is the function:
def preprocess(
sources: Sequence[str],
targets: Sequence[str],
tokenizer: transformers.PreTrainedTokenizer,
skip_tokens:Sequence[int],
context_markups: Sequence[int],
) -> Dict:
"""Preprocess the data by tokenizing."""
examples = [s + t for s, t in zip(sources, targets)]
examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
input_ids = examples_tokenized["input_ids"]
labels = copy.deepcopy(input_ids)
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
label[:source_len] = IGNORE_INDEX
# special token mask
if skip_tokens is not None:
for i, input_id_list in enumerate(input_ids):
for j, orig_token in enumerate(input_id_list):
if orig_token in skip_tokens:
labels[i][j] = IGNORE_INDEX
if context_markups is not None:
for i, (label_id_list, source_len) in enumerate(zip(labels, sources_tokenized["input_ids_lens"])):
context_start = False
for j, orig_token in enumerate(label_id_list[source_len:]):
if context_start is False and orig_token == context_markups[0]:
context_start = True
start_idx = j+source_len
for k, orig_token_2 in enumerate(label_id_list[start_idx:]):
if orig_token_2 == context_markups[1]:
end_idx = start_idx + k
labels[i][start_idx+1:end_idx] = IGNORE_INDEX
context_start = False
return dict(input_ids=input_ids, labels=labels) | Preprocess the data by tokenizing. |
153,323 | import copy
import logging
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import torch
import transformers
from torch.utils.data import Dataset
from transformers import Trainer
import json
import io
import os
from ..retrieval_lm.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
DEFAULT_PAD_TOKEN = "[PAD]"
DEFAULT_EOS_TOKEN = "</s>"
DEFAULT_BOS_TOKEN = "<s>"
DEFAULT_UNK_TOKEN = "<unk>"
class ModelArguments:
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
tokenizer_path: Optional[str] = field(default=None)
use_special_token: bool = field(
default=False,
metadata={
"help": "Use special command during training."
},
)
not_consider_special_tokens: bool = field(
default=False,
metadata={
"help": "Consider special tokens during loss calculations."
},
)
use_context_markups: bool = field(
default=False,
metadata={
"help": "make separated training data."
},
)
use_flash_attn: bool = field(
default=False,
metadata={
"help": "use flash attention."
},
)
class DataArguments:
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
separated: bool = field(
default=False,
metadata={
"help": "make separated training data."
},
)
class TrainingArguments(transformers.TrainingArguments):
cache_dir: Optional[str] = field(default=None)
optim: str = field(default="adamw_torch")
model_max_length: int = field(
default=512,
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
)
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
"""Collects the state dict and dump to disk."""
state_dict = trainer.model.state_dict()
if trainer.args.should_save:
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
del state_dict
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
def smart_tokenizer_and_embedding_resize(
special_tokens_dict: Dict,
tokenizer: transformers.PreTrainedTokenizer,
model: transformers.PreTrainedModel,
):
"""Resize tokenizer and embedding.
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
"""
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
print("# of new special tokens: {}".format(num_new_tokens))
model.resize_token_embeddings(len(tokenizer))
if num_new_tokens > 0:
input_embeddings = model.get_input_embeddings().weight.data
output_embeddings = model.get_output_embeddings().weight.data
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
input_embeddings[-num_new_tokens:] = input_embeddings_avg
output_embeddings[-num_new_tokens:] = output_embeddings_avg
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args, skip_tokens=None, context_markups=None) -> Dict:
"""Make dataset and collator for supervised fine-tuning."""
train_dataset = SupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, skip_tokens=skip_tokens, context_markups=context_markups, separated=data_args.separated)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
def replace_llama_attn_with_flash_attn():
transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
_prepare_decoder_attention_mask
)
transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
def train():
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
if model_args.use_flash_attn:
replace_llama_attn_with_flash_attn()
model = transformers.AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
cache_dir=training_args.cache_dir,
)
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_args.model_name_or_path if model_args.tokenizer_path is None else model_args.tokenizer_path,
cache_dir=training_args.cache_dir,
model_max_length=training_args.model_max_length,
padding_side="right",
use_fast=False,
)
if "llama" in model_args.model_name_or_path:
tokenizer.add_special_tokens(
{
"eos_token": DEFAULT_EOS_TOKEN,
"bos_token": DEFAULT_BOS_TOKEN,
"unk_token": DEFAULT_UNK_TOKEN,
}
)
# add special tokens
if model_args.use_special_token is True:
special_token_dict = {"additional_special_tokens": ["[No Retrieval]", "[Retrieval]", "[Continue to Use Evidence]", "[Irrelevant]", "[Relevant]", "<paragraph>", "</paragraph>", "[Utility:1]", "[Utility:2]", "[Utility:3]", "[Utility:4]", "[Utility:5]", "[Fully supported]", "[Partially supported]", "[No support / Contradictory]"]}
if tokenizer.pad_token is None:
special_token_dict["pad_token"] = DEFAULT_PAD_TOKEN
smart_tokenizer_and_embedding_resize(
special_tokens_dict=special_token_dict,
tokenizer=tokenizer,
model=model,
)
else:
if tokenizer.pad_token is None:
smart_tokenizer_and_embedding_resize(
special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
tokenizer=tokenizer,
model=model,
)
if model_args.use_special_token is True:
special_tokens = tokenizer.additional_special_tokens
skip_tokens = []
context_markups = []
if model_args.use_context_markups is True:
for token in ["<paragraph>", "</paragraph>"]:
context_markups.append(tokenizer.convert_tokens_to_ids(token))
if model_args.not_consider_special_tokens is True:
skip_tokens = []
for token in special_tokens:
skip_tokens.append(tokenizer.convert_tokens_to_ids(token))
else:
skip_tokens = None
data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args, skip_tokens=skip_tokens, context_markups=context_markups)
else:
data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
else:
data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
trainer.train()
trainer.save_state()
safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir) | null |
153,324 | import spacy
import jsonlines
from transformers import AutoTokenizer, AutoModelForCausalLM
from vllm import LLM, SamplingParams
import random
import torch
import os
import numpy as np
import openai
from tqdm import tqdm
import json
import argparse
import ast
import re
from tqdm import tqdm
from collections import Counter
import string
import sys
import time
from utils import PROMPT_DICT, TASK_INST, load_jsonlines, control_tokens, load_special_tokens
from metrics import match, accuracy
np.random.seed(seed)
def postprocess_answer_option_conditioned(answer):
for token in control_tokens:
answer = answer.replace(token, "")
if "</s>" in answer:
answer = answer.replace("</s>", "")
if "\n" in answer:
answer = answer.replace("\n", "")
if "<|endoftext|>" in answer:
answer = answer.replace("<|endoftext|>", "")
return answer
def call_model_rerank_w_scores_batch(prompt, evidences, model, max_new_tokens=15,
ret_tokens=None, rel_tokens=None, grd_tokens=None, ut_tokens=None,
use_seqscore=False, threshold=0.5,
w_rel=1.0, w_sup=1.0, w_use=0.5, mode="adaptive_retrieval", closed=False):
results = {}
if mode != "always_retrieve":
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, max_tokens=max_new_tokens, logprobs=32016)
preds = model.generate([prompt], sampling_params)
pred_token_ids = preds[0].outputs[0].token_ids
pred_text = preds[0].outputs[0].text
pred_log_probs = preds[0].outputs[0].logprobs
results["no_retrieval"] = pred_text
# save relevance token scores
if mode == "always_retrieve":
do_retrieve = True
elif mode == "no_retrieval":
do_retrieve = False
else:
if threshold is not None:
score_dict = {}
for tok, id in ret_tokens.items():
if id not in pred_log_probs[0]:
score_dict[tok] = -100
prob = pred_log_probs[0][id]
score_dict[tok] = float(prob)
do_retrieve = score_dict["[Retrieval]"] / (
score_dict["[Retrieval]"] + score_dict["[No Retrieval]"]) > threshold
else:
do_retrieve = "[Retrieval]" in pred
if do_retrieve is True:
evidence_augmented_inputs = [prompt + "[Retrieval]<paragraph>{0}\n{1}</paragraph>".format(
para["title"], para["text"]) for para in evidences]
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, max_tokens=max_new_tokens, logprobs=5000)
preds = model.generate(evidence_augmented_inputs, sampling_params)
relevance_score_dict = {}
grd_score_dict = {}
ut_score_dict = {}
overall_scores = {}
for p_idx, pred in enumerate(preds):
pred_token_ids = pred.outputs[0].token_ids
pred_text = pred.outputs[0].text
pred_log_probs = pred.outputs[0].logprobs
seq_score = pred.outputs[0].cumulative_logprob / \
max(len(pred.outputs[0].token_ids), 1)
relevance_score_dict.setdefault(p_idx, {})
grd_score_dict.setdefault(p_idx, {})
ut_score_dict.setdefault(p_idx, {})
# Compute reward scores
for tok, id in rel_tokens.items():
prob = pred_log_probs[0][id] if id in pred_log_probs[0] else -100
relevance_score_dict[p_idx][tok] = np.exp(float(prob))
if grd_tokens is not None:
groundness_token_appear_indices = []
for tok_idx, tok in enumerate(pred_token_ids):
if tok in list(grd_tokens.values()):
groundness_token_appear_indices.append(tok_idx)
break
if len(groundness_token_appear_indices) > 0:
idx = groundness_token_appear_indices[0]
for token, token_id in grd_tokens.items():
prob = pred_log_probs[idx][token_id] if token_id in pred_log_probs[idx] else -100
grd_score_dict[p_idx][token] = np.exp(float(prob))
if ut_tokens is not None:
utility_token_appear_indices = []
for tok_idx, tok in enumerate(pred_token_ids):
if tok in list(ut_tokens.values()):
utility_token_appear_indices.append(tok_idx)
if len(utility_token_appear_indices) > 0:
idx = utility_token_appear_indices[0]
for token, token_id in ut_tokens.items():
prob = pred_log_probs[idx][token_id] if token_id in pred_log_probs[idx] else -100
ut_score_dict[p_idx][token] = np.exp(float(prob))
relevance_score = relevance_score_dict[p_idx]["[Relevant]"] / (
np.sum(list(relevance_score_dict[p_idx].values())))
if len(grd_score_dict[p_idx]) == 3:
gt_sum = np.sum(list(grd_score_dict[p_idx].values()))
ground_score = (grd_score_dict[p_idx]["[Fully supported]"] / gt_sum) + 0.5 * (
grd_score_dict[p_idx]["[Partially supported]"] / gt_sum)
else:
ground_score = 0.0
if len(ut_score_dict[p_idx]) == 5:
ut_sum = np.sum(list(ut_score_dict[p_idx].values()))
ut_scores = [-1, -0.5, 0, 0.5, 1]
utility_score = np.sum(
[ut_scores[i] * (ut_score_dict[p_idx]["[Utility:{}]".format(i+1)] / ut_sum) for i in range(len(ut_scores))])
else:
utility_score = 0.0
if use_seqscore is True:
final_score = np.exp(seq_score) + w_rel * relevance_score + \
w_sup * ground_score + w_use * utility_score
else:
final_score = w_rel * relevance_score + \
w_sup * ground_score + w_use * utility_score
overall_scores[p_idx] = {"final_score": final_score,
"relevance_score": relevance_score,
"ground_score": ground_score,
"utility_score": utility_score,
"relevance_score_dict": relevance_score_dict,
"grd_score_dict": grd_score_dict,
"ut_score_dict": utility_score}
results["retrieval_{}".format(p_idx)] = {
"pred": pred_text, "score": final_score, "ctx": evidences[p_idx]}
else:
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, max_tokens=max_new_tokens)
prompt += "[No Retrieval]"
preds = model.generate([prompt], sampling_params)
pred = preds[0].outputs[0].text
# Aggregating answers
if len(results) == 1:
postprocessed_pred = postprocess_answer_option_conditioned(pred)
return postprocessed_pred, results, do_retrieve
else:
answer2score = {}
if closed is True:
for key, result in results.items():
if key == "no_retrieval":
continue
answer = postprocess_answer_option_conditioned(result["pred"])
score = result["score"]
answer2score.setdefault(answer, 0)
answer2score[answer] += score
sorted_answers = sorted(
answer2score.items(), key=lambda x: x[1], reverse=True)
best_option = sorted_answers[0][0]
else:
path2score = {key: item["score"] for key,
item in results.items() if key != "no_retrieval"}
best_path = sorted(path2score.items(),
key=lambda x: x[1], reverse=True)[0][0]
best_option = results[best_path]["pred"]
return best_option, results, do_retrieve | null |
153,325 | import spacy
import jsonlines
from transformers import AutoTokenizer, AutoModelForCausalLM
from vllm import LLM, SamplingParams
import random
import torch
import os
import numpy as np
import openai
from tqdm import tqdm
import json
import argparse
import ast
import re
from tqdm import tqdm
from collections import Counter
import string
import sys
import time
from utils import PROMPT_DICT, TASK_INST, load_jsonlines, control_tokens, load_special_tokens
from metrics import match, accuracy
PROMPT_DICT = {
"prompt_input": (
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n"
),
"prompt_no_input": (
"### Instruction:\n{instruction}\n\n### Response:\n"
),
"prompt_no_input_retrieval": (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
"### Paragraph:\n{paragraph}\n\n### Instruction:\n{instruction}\n\n### Response:"
),
"prompt_open_instruct": (
"<user>\n{instruction}\n"
"<assistant>\n"
),
"prompt_open_instruct_retrieval": (
"<user>\nReference:{paragraph}\n{instruction}\n"
"<assistant>\n"
),
"llama_chat_prompt": (
"[INST]{instruction}[/INST]"
),
"llama_chat_prompt_retrieval": (
"[INST]{paragraph}\n{instruction}[/INST]"
),
}
def process_data_evidences(demonstration, top_n):
ctx_key = "ctxs" if "ctxs" in demonstration else "top_contexts"
prompt = PROMPT_DICT["prompt_no_input"].format_map(demonstration)
evidences = demonstration[ctx_key][:top_n]
return prompt, evidences | null |
153,326 | import spacy
import jsonlines
from transformers import AutoTokenizer, AutoModelForCausalLM
from vllm import LLM, SamplingParams
import random
import torch
import os
import numpy as np
import openai
from tqdm import tqdm
import json
import argparse
import ast
import re
from tqdm import tqdm
from collections import Counter
import string
import sys
import time
from utils import PROMPT_DICT, TASK_INST, load_jsonlines, control_tokens, load_special_tokens
from metrics import match, accuracy
TASK_INST = {"wow": "Given a chat history separated by new lines, generates an informative, knowledgeable and engaging response. ",
"fever": "Is the following statement correct or not? Say true if it's correct; otherwise say false.",
"eli5": "Provide a paragraph-length response using simple words to answer the following question.",
"obqa": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"arc_easy": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"arc_c": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"trex": "Given the input format 'Subject Entity [SEP] Relationship Type,' predict the target entity.",
"asqa": "Answer the following question. The question may be ambiguous and have multiple correct answers, and in that case, you have to provide a long-form answer including all correct answers."}
def preprocess_input_data(dataset, task=None):
new_data = []
if task in TASK_INST:
instruction = TASK_INST[task]
else:
instruction = None
for item in dataset:
if task == "arc_c":
choices = item["choices"]
answer_labels = {}
for i in range(len(choices["label"])):
answer_key = choices["label"][i]
text = choices["text"][i]
if answer_key == "1":
answer_labels["A"] = text
if answer_key == "2":
answer_labels["B"] = text
if answer_key == "3":
answer_labels["C"] = text
if answer_key == "4":
answer_labels["D"] = text
if answer_key in ["A", "B", "C", "D"]:
answer_labels[answer_key] = text
if "D" not in answer_labels:
answer_labels["D"] = ""
choices = "\nA: {0}\nB: {1}\nC: {2}\nD: {3}".format(
answer_labels["A"], answer_labels["B"], answer_labels["C"], answer_labels["D"])
if "E" in answer_labels:
choices += "\nE: {}".format(answer_labels["E"])
item["instruction"] = instruction + \
"\n\n### Input:\n" + item["question"] + choices
item["answers"] = [item["answerKey"]]
else:
prompt = instruction + "\n\n## Input:\n\n" + \
item["question"] if instruction is not None else item["question"]
item["instruction"] = prompt
new_data.append(item)
return new_data | null |
153,327 | import jsonlines
import json
import copy
import re
retrieval_tokens_names = ["[No Retrieval]",
"[Retrieval]", "[Continue to Use Evidence]"]
utility_tokens_names = ["[Utility:1]", "[Utility:2]",
"[Utility:3]", "[Utility:4]", "[Utility:5]"]
ground_tokens_names = ["[Fully supported]",
"[Partially supported]", "[No support / Contradictory]"]
def load_special_tokens(tokenizer, use_grounding=False, use_utility=False):
ret_tokens = {token: tokenizer.convert_tokens_to_ids(
token) for token in retrieval_tokens_names}
rel_tokens = {}
for token in ["[Irrelevant]", "[Relevant]"]:
rel_tokens[token] = tokenizer.convert_tokens_to_ids(token)
grd_tokens = None
if use_grounding is True:
grd_tokens = {}
for token in ground_tokens_names:
grd_tokens[token] = tokenizer.convert_tokens_to_ids(token)
ut_tokens = None
if use_utility is True:
ut_tokens = {}
for token in utility_tokens_names:
ut_tokens[token] = tokenizer.convert_tokens_to_ids(token)
return ret_tokens, rel_tokens, grd_tokens, ut_tokens | null |
153,328 | import jsonlines
import json
import copy
import re
def fix_spacing(input_text):
# Add a space after periods that lack whitespace
output_text = re.sub(r'(?<=\w)([.!?])(?=\w)', r'\1 ', input_text)
return output_text | null |
153,329 | import jsonlines
import json
import copy
import re
def load_jsonlines(file):
with jsonlines.open(file, 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
return lst
def load_file(input_fp):
if input_fp.endswith(".json"):
input_data = json.load(open(input_fp))
else:
input_data = load_jsonlines(input_fp)
return input_data | null |
153,330 | import jsonlines
import json
import copy
import re
def save_file_jsonl(data, fp):
with jsonlines.open(fp, mode='w') as writer:
writer.write_all(data) | null |
153,331 | import jsonlines
import json
import copy
import re
TASK_INST = {"wow": "Given a chat history separated by new lines, generates an informative, knowledgeable and engaging response. ",
"fever": "Is the following statement correct or not? Say true if it's correct; otherwise say false.",
"eli5": "Provide a paragraph-length response using simple words to answer the following question.",
"obqa": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"arc_easy": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"arc_c": "Given four answer candidates, A, B, C and D, choose the best answer choice.",
"trex": "Given the input format 'Subject Entity [SEP] Relationship Type,' predict the target entity.",
"asqa": "Answer the following question. The question may be ambiguous and have multiple correct answers, and in that case, you have to provide a long-form answer including all correct answers."}
def preprocess_input(input_data, task):
if task == "factscore":
for item in input_data:
item["instruction"] = item["input"]
item["output"] = [item["output"]
] if "output" in item else [item["topic"]]
return input_data
elif task == "qa":
for item in input_data:
if "instruction" not in item:
item["instruction"] = item["question"]
if "answers" not in item and "output" in item:
item["answers"] = "output"
return input_data
elif task in ["asqa", "eli5"]:
processed_input_data = []
for instance_idx, item in enumerate(input_data["data"]):
prompt = item["question"]
instructions = TASK_INST[task]
prompt = instructions + "## Input:\n\n" + prompt
entry = copy.deepcopy(item)
entry["instruction"] = prompt
processed_input_data.append(entry)
return processed_input_data | null |
153,332 | import jsonlines
import json
import copy
import re
def process_arc_instruction(item, instruction):
choices = item["choices"]
answer_labels = {}
for i in range(len(choices["label"])):
answer_key = choices["label"][i]
text = choices["text"][i]
if answer_key == "1":
answer_labels["A"] = text
if answer_key == "2":
answer_labels["B"] = text
if answer_key == "3":
answer_labels["C"] = text
if answer_key == "4":
answer_labels["D"] = text
if answer_key in ["A", "B", "C", "D"]:
answer_labels[answer_key] = text
if "D" not in answer_labels:
answer_labels["D"] = ""
choices = "\nA: {0}\nB: {1}\nC: {2}\nD: {3}".format(answer_labels["A"], answer_labels["B"], answer_labels["C"], answer_labels["D"])
if "E" in answer_labels:
choices += "\nE: {}".format(answer_labels["E"])
processed_instruction = instruction + "\n\n### Input:\n" + item["instruction"] + choices
return processed_instruction | null |
153,333 | import jsonlines
import json
import copy
import re
def postprocess_answers_closed(output, task, choices=None):
final_output = None
if choices is not None:
for c in choices.split(" "):
if c in output:
final_output = c
if task == "fever" and output in ["REFUTES", "SUPPORTS"]:
final_output = "true" if output == "SUPPORTS" else "REFUTES"
if task == "fever" and output.lower() in ["true", "false"]:
final_output = output.lower()
if final_output is None:
return output
else:
return final_output | null |
153,334 | import os
import sys
import logging
import torch
import errno
from typing import Union, Tuple, List, Dict
from collections import defaultdict
from src import dist_utils
logger = logging.getLogger(__name__)
def init_logger(args, stdout_only=False):
if torch.distributed.is_initialized():
torch.distributed.barrier()
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [stdout_handler]
if not stdout_only:
file_handler = logging.FileHandler(filename=os.path.join(args.output_dir, "run.log"))
handlers.append(file_handler)
logging.basicConfig(
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO if dist_utils.is_main() else logging.WARN,
format="[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s",
handlers=handlers,
)
return logger | null |
153,335 | import os
import sys
import logging
import torch
import errno
from typing import Union, Tuple, List, Dict
from collections import defaultdict
from src import dist_utils
logger = logging.getLogger(__name__)
def symlink_force(target, link_name):
def save(model, optimizer, scheduler, step, opt, dir_path, name):
model_to_save = model.module if hasattr(model, "module") else model
path = os.path.join(dir_path, "checkpoint")
epoch_path = os.path.join(path, name) # "step-%s" % step)
os.makedirs(epoch_path, exist_ok=True)
cp = os.path.join(path, "latest")
fp = os.path.join(epoch_path, "checkpoint.pth")
checkpoint = {
"step": step,
"model": model_to_save.state_dict(),
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict(),
"opt": opt,
}
torch.save(checkpoint, fp)
symlink_force(epoch_path, cp)
if not name == "lastlog":
logger.info(f"Saving model to {epoch_path}") | null |
153,336 | import os
import sys
import logging
import torch
import errno
from typing import Union, Tuple, List, Dict
from collections import defaultdict
from src import dist_utils
def get_parameters(net, verbose=False):
num_params = 0
for param in net.parameters():
num_params += param.numel()
message = "[Network] Total number of parameters : %.6f M" % (num_params / 1e6)
return message | null |
153,337 | import os
import sys
import logging
import torch
import errno
from typing import Union, Tuple, List, Dict
from collections import defaultdict
from src import dist_utils
logger = logging.getLogger(__name__)
def init_tb_logger(output_dir):
try:
from torch.utils import tensorboard
if dist_utils.is_main():
tb_logger = tensorboard.SummaryWriter(output_dir)
else:
tb_logger = None
except:
logger.warning("Tensorboard is not available.")
tb_logger = None
return tb_logger | null |
153,338 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def load_dataset(data_path, loading_mode):
files = glob.glob(os.path.join(data_path, "*.p*"))
files.sort()
tensors = []
if loading_mode == "split":
files_split = list(np.array_split(files, dist_utils.get_world_size()))[dist_utils.get_rank()]
for filepath in files_split:
try:
tensors.append(torch.load(filepath, map_location="cpu"))
except:
logger.warning(f"Unable to load file {filepath}")
elif loading_mode == "full":
for fin in files:
tensors.append(torch.load(fin, map_location="cpu"))
elif loading_mode == "single":
tensors.append(torch.load(files[0], map_location="cpu"))
if len(tensors) == 0:
return None
tensor = torch.cat(tensors)
return tensor
class MultiDataset(torch.utils.data.Dataset):
def __init__(self, datasets):
self.datasets = datasets
self.prob = [1 / len(self.datasets) for _ in self.datasets]
self.dataset_ids = list(self.datasets.keys())
def __len__(self):
return sum([len(dataset) for dataset in self.datasets.values()])
def __getitem__(self, index):
dataset_idx = numpy.random.choice(range(len(self.prob)), 1, p=self.prob)[0]
did = self.dataset_ids[dataset_idx]
index = random.randint(0, len(self.datasets[did]) - 1)
sample = self.datasets[did][index]
sample["dataset_id"] = did
return sample
def generate_offset(self):
for dataset in self.datasets.values():
dataset.generate_offset()
def set_prob(self, coeff=0.0):
prob = np.array([float(len(dataset)) for _, dataset in self.datasets.items()])
prob /= prob.sum()
prob = np.array([p**coeff for p in prob])
prob /= prob.sum()
self.prob = prob
class Dataset(torch.utils.data.Dataset):
"""Monolingual dataset based on a list of paths"""
def __init__(self, data, chunk_length, tokenizer, opt):
self.data = data
self.chunk_length = chunk_length
self.tokenizer = tokenizer
self.opt = opt
self.generate_offset()
def __len__(self):
return (self.data.size(0) - self.offset) // self.chunk_length
def __getitem__(self, index):
start_idx = self.offset + index * self.chunk_length
end_idx = start_idx + self.chunk_length
tokens = self.data[start_idx:end_idx]
q_tokens = randomcrop(tokens, self.opt.ratio_min, self.opt.ratio_max)
k_tokens = randomcrop(tokens, self.opt.ratio_min, self.opt.ratio_max)
q_tokens = apply_augmentation(q_tokens, self.opt)
q_tokens = add_bos_eos(q_tokens, self.tokenizer.bos_token_id, self.tokenizer.eos_token_id)
k_tokens = apply_augmentation(k_tokens, self.opt)
k_tokens = add_bos_eos(k_tokens, self.tokenizer.bos_token_id, self.tokenizer.eos_token_id)
return {"q_tokens": q_tokens, "k_tokens": k_tokens}
def generate_offset(self):
self.offset = random.randint(0, self.chunk_length - 1)
def load_data(opt, tokenizer):
datasets = {}
for path in opt.train_data:
data = load_dataset(path, opt.loading_mode)
if data is not None:
datasets[path] = Dataset(data, opt.chunk_length, tokenizer, opt)
dataset = MultiDataset(datasets)
dataset.set_prob(coeff=opt.sampling_coefficient)
return dataset | null |
153,339 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def randomcrop(x, ratio_min, ratio_max):
ratio = random.uniform(ratio_min, ratio_max)
length = int(len(x) * ratio)
start = random.randint(0, len(x) - length)
end = start + length
crop = x[start:end].clone()
return crop | null |
153,340 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def build_mask(tensors):
shapes = [x.shape for x in tensors]
maxlength = max([len(x) for x in tensors])
returnmasks = []
ids = []
for k, x in enumerate(tensors):
returnmasks.append(torch.tensor([1] * len(x) + [0] * (maxlength - len(x))))
ids.append(torch.cat((x, torch.tensor([0] * (maxlength - len(x))))))
ids = torch.stack(ids, dim=0).long()
returnmasks = torch.stack(returnmasks, dim=0).bool()
return ids, returnmasks | null |
153,341 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def add_token(x, token):
x = torch.cat((torch.tensor([token]), x))
return x | null |
153,342 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def deleteword(x, p=0.1):
mask = np.random.rand(len(x))
x = [e for e, m in zip(x, mask) if m > p]
return x
def replaceword(x, min_random, max_random, p=0.1):
mask = np.random.rand(len(x))
x = [e if m > p else random.randint(min_random, max_random) for e, m in zip(x, mask)]
return x
def maskword(x, mask_id, p=0.1):
mask = np.random.rand(len(x))
x = [e if m > p else mask_id for e, m in zip(x, mask)]
return x
def shuffleword(x, p=0.1):
count = (np.random.rand(len(x)) < p).sum()
"""Shuffles any n number of values in a list"""
indices_to_shuffle = random.sample(range(len(x)), k=count)
to_shuffle = [x[i] for i in indices_to_shuffle]
random.shuffle(to_shuffle)
for index, value in enumerate(to_shuffle):
old_index = indices_to_shuffle[index]
x[old_index] = value
return x
def apply_augmentation(x, opt):
if opt.augmentation == "mask":
return torch.tensor(maskword(x, mask_id=opt.mask_id, p=opt.prob_augmentation))
elif opt.augmentation == "replace":
return torch.tensor(
replaceword(x, min_random=opt.start_id, max_random=opt.vocab_size - 1, p=opt.prob_augmentation)
)
elif opt.augmentation == "delete":
return torch.tensor(deleteword(x, p=opt.prob_augmentation))
elif opt.augmentation == "shuffle":
return torch.tensor(shuffleword(x, p=opt.prob_augmentation))
else:
if not isinstance(x, torch.Tensor):
x = torch.Tensor(x)
return x | null |
153,343 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
def add_bos_eos(x, bos_token_id, eos_token_id):
if not isinstance(x, torch.Tensor):
x = torch.Tensor(x)
if bos_token_id is None and eos_token_id is not None:
x = torch.cat([x.clone().detach(), torch.tensor([eos_token_id])])
elif bos_token_id is not None and eos_token_id is None:
x = torch.cat([torch.tensor([bos_token_id]), x.clone().detach()])
elif bos_token_id is None and eos_token_id is None:
pass
else:
x = torch.cat([torch.tensor([bos_token_id]), x.clone().detach(), torch.tensor([eos_token_id])])
return x | null |
153,344 | import os
import glob
import torch
import random
import json
import csv
import numpy as np
import numpy.random
import logging
from collections import defaultdict
import torch.distributed as dist
from src import dist_utils
logger = logging.getLogger(__name__)
def load_passages(path):
if not os.path.exists(path):
logger.info(f"{path} does not exist")
return
logger.info(f"Loading passages from: {path}")
passages = []
with open(path) as fin:
if path.endswith(".jsonl"):
for k, line in enumerate(fin):
ex = json.loads(line)
passages.append(ex)
else:
reader = csv.reader(fin, delimiter="\t")
for k, row in enumerate(reader):
if not row[0] == "id":
ex = {"id": row[0], "title": row[2], "text": row[1]}
passages.append(ex)
return passages | null |
153,345 | import collections
import logging
import regex
import string
import unicodedata
from functools import partial
from multiprocessing import Pool as ProcessPool
from typing import Tuple, List, Dict
import numpy as np
class SimpleTokenizer(object):
ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+'
NON_WS = r'[^\p{Z}\p{C}]'
def __init__(self):
"""
Args:
annotators: None or empty set (only tokenizes).
"""
self._regexp = regex.compile(
'(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS),
flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE
)
def tokenize(self, text, uncased=False):
matches = [m for m in self._regexp.finditer(text)]
if uncased:
tokens = [m.group().lower() for m in matches]
else:
tokens = [m.group() for m in matches]
return tokens
logger = logging.getLogger(__name__)
QAMatchStats = collections.namedtuple('QAMatchStats', ['top_k_hits', 'questions_doc_hits'])
def check_answer(example, tokenizer) -> List[bool]:
"""Search through all the top docs to see if they have any of the answers."""
answers = example['answers']
ctxs = example['ctxs']
hits = []
for i, doc in enumerate(ctxs):
text = doc['text']
if text is None: # cannot find the document for some reason
logger.warning("no doc in db")
hits.append(False)
continue
hits.append(has_answer(answers, text, tokenizer))
return hits
The provided code snippet includes necessary dependencies for implementing the `calculate_matches` function. Write a Python function `def calculate_matches(data: List, workers_num: int)` to solve the following problem:
Evaluates answers presence in the set of documents. This function is supposed to be used with a large collection of documents and results. It internally forks multiple sub-processes for evaluation and then merges results :param all_docs: dictionary of the entire documents database. doc_id -> (doc_text, title) :param answers: list of answers's list. One list per question :param closest_docs: document ids of the top results along with their scores :param workers_num: amount of parallel threads to process data :param match_type: type of answer matching. Refer to has_answer code for available options :return: matching information tuple. top_k_hits - a list where the index is the amount of top documents retrieved and the value is the total amount of valid matches across an entire dataset. questions_doc_hits - more detailed info with answer matches for every question and every retrieved document
Here is the function:
def calculate_matches(data: List, workers_num: int):
"""
Evaluates answers presence in the set of documents. This function is supposed to be used with a large collection of
documents and results. It internally forks multiple sub-processes for evaluation and then merges results
:param all_docs: dictionary of the entire documents database. doc_id -> (doc_text, title)
:param answers: list of answers's list. One list per question
:param closest_docs: document ids of the top results along with their scores
:param workers_num: amount of parallel threads to process data
:param match_type: type of answer matching. Refer to has_answer code for available options
:return: matching information tuple.
top_k_hits - a list where the index is the amount of top documents retrieved and the value is the total amount of
valid matches across an entire dataset.
questions_doc_hits - more detailed info with answer matches for every question and every retrieved document
"""
logger.info('Matching answers in top docs...')
tokenizer = SimpleTokenizer()
get_score_partial = partial(check_answer, tokenizer=tokenizer)
processes = ProcessPool(processes=workers_num)
scores = processes.map(get_score_partial, data)
logger.info('Per question validation results len=%d', len(scores))
n_docs = len(data[0]['ctxs'])
top_k_hits = [0] * n_docs
for question_hits in scores:
best_hit = next((i for i, x in enumerate(question_hits) if x), None)
if best_hit is not None:
top_k_hits[best_hit:] = [v + 1 for v in top_k_hits[best_hit:]]
return QAMatchStats(top_k_hits, scores) | Evaluates answers presence in the set of documents. This function is supposed to be used with a large collection of documents and results. It internally forks multiple sub-processes for evaluation and then merges results :param all_docs: dictionary of the entire documents database. doc_id -> (doc_text, title) :param answers: list of answers's list. One list per question :param closest_docs: document ids of the top results along with their scores :param workers_num: amount of parallel threads to process data :param match_type: type of answer matching. Refer to has_answer code for available options :return: matching information tuple. top_k_hits - a list where the index is the amount of top documents retrieved and the value is the total amount of valid matches across an entire dataset. questions_doc_hits - more detailed info with answer matches for every question and every retrieved document |
153,346 | import collections
import logging
import regex
import string
import unicodedata
from functools import partial
from multiprocessing import Pool as ProcessPool
from typing import Tuple, List, Dict
import numpy as np
def f1(prediction, ground_truth):
def f1_score(prediction, ground_truths):
return max([f1(prediction, gt) for gt in ground_truths]) | null |
153,347 | import collections
import logging
import regex
import string
import unicodedata
from functools import partial
from multiprocessing import Pool as ProcessPool
from typing import Tuple, List, Dict
import numpy as np
def em(prediction, ground_truth):
return normalize_answer(prediction) == normalize_answer(ground_truth)
def exact_match_score(prediction, ground_truths):
return max([em(prediction, gt) for gt in ground_truths]) | null |
153,348 | import collections
import logging
import regex
import string
import unicodedata
from functools import partial
from multiprocessing import Pool as ProcessPool
from typing import Tuple, List, Dict
import numpy as np
def score(x, inversions, avg_topk, idx_topk):
x = np.array(x)
inversions.append(count_inversions(x))
for k in avg_topk:
# ratio of passages in the predicted top-k that are
# also in the topk given by gold score
avg_pred_topk = (x[:k]<k).mean()
avg_topk[k].append(avg_pred_topk)
for k in idx_topk:
below_k = (x<k)
# number of passages required to obtain all passages from gold top-k
idx_gold_topk = len(x) - np.argmax(below_k[::-1])
idx_topk[k].append(idx_gold_topk)
def eval_batch(scores, inversions, avg_topk, idx_topk):
for k, s in enumerate(scores):
s = s.cpu().numpy()
sorted_idx = np.argsort(-s)
score(sorted_idx, inversions, avg_topk, idx_topk) | null |
153,349 | import torch
import torch.distributed as dist
class Gather(torch.autograd.Function):
def forward(ctx, x: torch.tensor):
def backward(ctx, *grads):
def gather(x: torch.tensor):
if not dist.is_initialized():
return x
x_gather = Gather.apply(x)
x_gather = torch.cat(x_gather, dim=0)
return x_gather | null |
153,350 | import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_initialized():
return 1
else:
return dist.get_world_size()
def gather_nograd(x: torch.tensor):
if not dist.is_initialized():
return x
x_gather = [torch.ones_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(x_gather, x, async_op=False)
x_gather = torch.cat(x_gather, dim=0)
return x_gather | null |
153,351 | import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_initialized():
return 1
else:
return dist.get_world_size()
The provided code snippet includes necessary dependencies for implementing the `varsize_gather_nograd` function. Write a Python function `def varsize_gather_nograd(x: torch.Tensor)` to solve the following problem:
gather tensors of different sizes along the first dimension
Here is the function:
def varsize_gather_nograd(x: torch.Tensor):
"""gather tensors of different sizes along the first dimension"""
if not dist.is_initialized():
return x
# determine max size
size = torch.tensor([x.shape[0]], device=x.device, dtype=torch.int)
allsizes = [torch.zeros_like(size) for _ in range(dist.get_world_size())]
dist.all_gather(allsizes, size)
max_size = max([size.cpu().max() for size in allsizes])
padded = torch.empty(max_size, *x.shape[1:], dtype=x.dtype, device=x.device)
padded[: x.shape[0]] = x
output = [torch.zeros_like(padded) for _ in range(dist.get_world_size())]
dist.all_gather(output, padded)
output = [tensor[: allsizes[k]] for k, tensor in enumerate(output)]
output = torch.cat(output, dim=0)
return output | gather tensors of different sizes along the first dimension |
153,352 | import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_initialized():
return 1
else:
return dist.get_world_size()
The provided code snippet includes necessary dependencies for implementing the `get_varsize` function. Write a Python function `def get_varsize(x: torch.Tensor)` to solve the following problem:
gather tensors of different sizes along the first dimension
Here is the function:
def get_varsize(x: torch.Tensor):
"""gather tensors of different sizes along the first dimension"""
if not dist.is_initialized():
return [x.shape[0]]
# determine max size
size = torch.tensor([x.shape[0]], device=x.device, dtype=torch.int)
allsizes = [torch.zeros_like(size) for _ in range(dist.get_world_size())]
dist.all_gather(allsizes, size)
allsizes = torch.cat(allsizes)
return allsizes | gather tensors of different sizes along the first dimension |
153,353 | import torch
import torch.distributed as dist
def is_main():
return get_rank() == 0
def get_world_size():
if not dist.is_initialized():
return 1
else:
return dist.get_world_size()
def average_main(x):
if not dist.is_initialized():
return x
if dist.is_initialized() and dist.get_world_size() > 1:
dist.reduce(x, 0, op=dist.ReduceOp.SUM)
if is_main():
x = x / dist.get_world_size()
return x | null |
153,354 | import torch
import torch.distributed as dist
def sum_main(x):
if not dist.is_initialized():
return x
if dist.is_initialized() and dist.get_world_size() > 1:
dist.reduce(x, 0, op=dist.ReduceOp.SUM)
return x
def weighted_average(x, count):
if not dist.is_initialized():
if isinstance(x, torch.Tensor):
x = x.item()
return x, count
t_loss = torch.tensor([x * count]).cuda()
t_total = torch.tensor([count]).cuda()
t_loss = sum_main(t_loss)
t_total = sum_main(t_total)
return (t_loss / t_total).item(), t_total.item() | null |
153,355 | import os
from collections import defaultdict
from typing import List, Dict
import numpy as np
import torch
import torch.distributed as dist
import beir.util
from beir.datasets.data_loader import GenericDataLoader
from beir.retrieval.evaluation import EvaluateRetrieval
from beir.retrieval.search.dense import DenseRetrievalExactSearch
from beir.reranking.models import CrossEncoder
from beir.reranking import Rerank
import src.dist_utils as dist_utils
from src import normalize_text
class DenseEncoderModel:
def __init__(
self,
query_encoder,
doc_encoder=None,
tokenizer=None,
max_length=512,
add_special_tokens=True,
norm_query=False,
norm_doc=False,
lower_case=False,
normalize_text=False,
**kwargs,
):
self.query_encoder = query_encoder
self.doc_encoder = doc_encoder
self.tokenizer = tokenizer
self.max_length = max_length
self.add_special_tokens = add_special_tokens
self.norm_query = norm_query
self.norm_doc = norm_doc
self.lower_case = lower_case
self.normalize_text = normalize_text
def encode_queries(self, queries: List[str], batch_size: int, **kwargs) -> np.ndarray:
if dist.is_initialized():
idx = np.array_split(range(len(queries)), dist.get_world_size())[dist.get_rank()]
else:
idx = range(len(queries))
queries = [queries[i] for i in idx]
if self.normalize_text:
queries = [normalize_text.normalize(q) for q in queries]
if self.lower_case:
queries = [q.lower() for q in queries]
allemb = []
nbatch = (len(queries) - 1) // batch_size + 1
with torch.no_grad():
for k in range(nbatch):
start_idx = k * batch_size
end_idx = min((k + 1) * batch_size, len(queries))
qencode = self.tokenizer.batch_encode_plus(
queries[start_idx:end_idx],
max_length=self.max_length,
padding=True,
truncation=True,
add_special_tokens=self.add_special_tokens,
return_tensors="pt",
)
qencode = {key: value.cuda() for key, value in qencode.items()}
emb = self.query_encoder(**qencode, normalize=self.norm_query)
allemb.append(emb.cpu())
allemb = torch.cat(allemb, dim=0)
allemb = allemb.cuda()
if dist.is_initialized():
allemb = dist_utils.varsize_gather_nograd(allemb)
allemb = allemb.cpu().numpy()
return allemb
def encode_corpus(self, corpus: List[Dict[str, str]], batch_size: int, **kwargs):
if dist.is_initialized():
idx = np.array_split(range(len(corpus)), dist.get_world_size())[dist.get_rank()]
else:
idx = range(len(corpus))
corpus = [corpus[i] for i in idx]
corpus = [c["title"] + " " + c["text"] if len(c["title"]) > 0 else c["text"] for c in corpus]
if self.normalize_text:
corpus = [normalize_text.normalize(c) for c in corpus]
if self.lower_case:
corpus = [c.lower() for c in corpus]
allemb = []
nbatch = (len(corpus) - 1) // batch_size + 1
with torch.no_grad():
for k in range(nbatch):
start_idx = k * batch_size
end_idx = min((k + 1) * batch_size, len(corpus))
cencode = self.tokenizer.batch_encode_plus(
corpus[start_idx:end_idx],
max_length=self.max_length,
padding=True,
truncation=True,
add_special_tokens=self.add_special_tokens,
return_tensors="pt",
)
cencode = {key: value.cuda() for key, value in cencode.items()}
emb = self.doc_encoder(**cencode, normalize=self.norm_doc)
allemb.append(emb.cpu())
allemb = torch.cat(allemb, dim=0)
allemb = allemb.cuda()
if dist.is_initialized():
allemb = dist_utils.varsize_gather_nograd(allemb)
allemb = allemb.cpu().numpy()
return allemb
def evaluate_model(
query_encoder,
doc_encoder,
tokenizer,
dataset,
batch_size=128,
add_special_tokens=True,
norm_query=False,
norm_doc=False,
is_main=True,
split="test",
score_function="dot",
beir_dir="BEIR/datasets",
save_results_path=None,
lower_case=False,
normalize_text=False,
):
metrics = defaultdict(list) # store final results
if hasattr(query_encoder, "module"):
query_encoder = query_encoder.module
query_encoder.eval()
if doc_encoder is not None:
if hasattr(doc_encoder, "module"):
doc_encoder = doc_encoder.module
doc_encoder.eval()
else:
doc_encoder = query_encoder
dmodel = DenseRetrievalExactSearch(
DenseEncoderModel(
query_encoder=query_encoder,
doc_encoder=doc_encoder,
tokenizer=tokenizer,
add_special_tokens=add_special_tokens,
norm_query=norm_query,
norm_doc=norm_doc,
lower_case=lower_case,
normalize_text=normalize_text,
),
batch_size=batch_size,
)
retriever = EvaluateRetrieval(dmodel, score_function=score_function)
data_path = os.path.join(beir_dir, dataset)
if not os.path.isdir(data_path) and is_main:
url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip".format(dataset)
data_path = beir.util.download_and_unzip(url, beir_dir)
dist_utils.barrier()
if not dataset == "cqadupstack":
corpus, queries, qrels = GenericDataLoader(data_folder=data_path).load(split=split)
results = retriever.retrieve(corpus, queries)
if is_main:
ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values)
for metric in (ndcg, _map, recall, precision, "mrr", "recall_cap", "hole"):
if isinstance(metric, str):
metric = retriever.evaluate_custom(qrels, results, retriever.k_values, metric=metric)
for key, value in metric.items():
metrics[key].append(value)
if save_results_path is not None:
torch.save(results, f"{save_results_path}")
elif dataset == "cqadupstack": # compute macroaverage over datasets
paths = glob.glob(data_path)
for path in paths:
corpus, queries, qrels = GenericDataLoader(data_folder=data_folder).load(split=split)
results = retriever.retrieve(corpus, queries)
if is_main:
ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values)
for metric in (ndcg, _map, recall, precision, "mrr", "recall_cap", "hole"):
if isinstance(metric, str):
metric = retriever.evaluate_custom(qrels, results, retriever.k_values, metric=metric)
for key, value in metric.items():
metrics[key].append(value)
for key, value in metrics.items():
assert (
len(value) == 12
), f"cqadupstack includes 12 datasets, only {len(value)} values were compute for the {key} metric"
metrics = {key: 100 * np.mean(value) for key, value in metrics.items()}
return metrics | null |
153,356 | from logging import getLogger
import os
import sys
import torch
import socket
import signal
import subprocess
def sig_handler(signum, frame):
logger.warning("Signal handler called with signal " + str(signum))
prod_id = int(os.environ['SLURM_PROCID'])
logger.warning("Host: %s - Global rank: %i" % (socket.gethostname(), prod_id))
if prod_id == 0:
logger.warning("Requeuing job " + os.environ['SLURM_JOB_ID'])
os.system('scontrol requeue ' + os.environ['SLURM_JOB_ID'])
else:
logger.warning("Not the main process, no need to requeue.")
sys.exit(-1)
def term_handler(signum, frame):
logger.warning("Signal handler called with signal " + str(signum))
logger.warning("Bypassing SIGTERM.")
The provided code snippet includes necessary dependencies for implementing the `init_signal_handler` function. Write a Python function `def init_signal_handler()` to solve the following problem:
Handle signals sent by SLURM for time limit / pre-emption.
Here is the function:
def init_signal_handler():
"""
Handle signals sent by SLURM for time limit / pre-emption.
"""
signal.signal(signal.SIGUSR1, sig_handler)
signal.signal(signal.SIGTERM, term_handler) | Handle signals sent by SLURM for time limit / pre-emption. |
153,357 | from logging import getLogger
import os
import sys
import torch
import socket
import signal
import subprocess
The provided code snippet includes necessary dependencies for implementing the `init_distributed_mode` function. Write a Python function `def init_distributed_mode(params)` to solve the following problem:
Handle single and multi-GPU / multi-node / SLURM jobs. Initialize the following variables: - local_rank - global_rank - world_size
Here is the function:
def init_distributed_mode(params):
"""
Handle single and multi-GPU / multi-node / SLURM jobs.
Initialize the following variables:
- local_rank
- global_rank
- world_size
"""
is_slurm_job = 'SLURM_JOB_ID' in os.environ and not 'WORLD_SIZE' in os.environ
has_local_rank = hasattr(params, 'local_rank')
# SLURM job without torch.distributed.launch
if is_slurm_job and has_local_rank:
assert params.local_rank == -1 # on the cluster, this is handled by SLURM
# local rank on the current node / global rank
params.local_rank = int(os.environ['SLURM_LOCALID'])
params.global_rank = int(os.environ['SLURM_PROCID'])
params.world_size = int(os.environ['SLURM_NTASKS'])
# define master address and master port
hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', os.environ['SLURM_JOB_NODELIST']])
params.main_addr = hostnames.split()[0].decode('utf-8')
assert 10001 <= params.main_port <= 20000 or params.world_size == 1
# set environment variables for 'env://'
os.environ['MASTER_ADDR'] = params.main_addr
os.environ['MASTER_PORT'] = str(params.main_port)
os.environ['WORLD_SIZE'] = str(params.world_size)
os.environ['RANK'] = str(params.global_rank)
is_distributed = True
# multi-GPU job (local or multi-node) - jobs started with torch.distributed.launch
elif has_local_rank and params.local_rank != -1:
assert params.main_port == -1
# read environment variables
params.global_rank = int(os.environ['RANK'])
params.world_size = int(os.environ['WORLD_SIZE'])
is_distributed = True
# local job (single GPU)
else:
params.local_rank = 0
params.global_rank = 0
params.world_size = 1
is_distributed = False
# set GPU device
torch.cuda.set_device(params.local_rank)
# initialize multi-GPU
if is_distributed:
# http://pytorch.apachecn.org/en/0.3.0/distributed.html#environment-variable-initialization
# 'env://' will read these environment variables:
# MASTER_PORT - required; has to be a free port on machine with rank 0
# MASTER_ADDR - required (except for rank 0); address of rank 0 node
# WORLD_SIZE - required; can be set either here, or in a call to init function
# RANK - required; can be set either here, or in a call to init function
#print("Initializing PyTorch distributed ...")
torch.distributed.init_process_group(
init_method='env://',
backend='nccl',
#world_size=params.world_size,
#rank=params.global_rank,
) | Handle single and multi-GPU / multi-node / SLURM jobs. Initialize the following variables: - local_rank - global_rank - world_size |
153,358 | import os
import torch
import transformers
from transformers import BertModel, XLMRobertaModel
from src import utils
class Contriever(BertModel):
def __init__(self, config, pooling="average", **kwargs):
super().__init__(config, add_pooling_layer=False)
if not hasattr(config, "pooling"):
self.config.pooling = pooling
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
normalize=False,
):
model_output = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
last_hidden = model_output["last_hidden_state"]
last_hidden = last_hidden.masked_fill(~attention_mask[..., None].bool(), 0.0)
if self.config.pooling == "average":
emb = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
elif self.config.pooling == "cls":
emb = last_hidden[:, 0]
if normalize:
emb = torch.nn.functional.normalize(emb, dim=-1)
return emb
class XLMRetriever(XLMRobertaModel):
def __init__(self, config, pooling="average", **kwargs):
super().__init__(config, add_pooling_layer=False)
if not hasattr(config, "pooling"):
self.config.pooling = pooling
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
normalize=False,
):
model_output = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
last_hidden = model_output["last_hidden_state"]
last_hidden = last_hidden.masked_fill(~attention_mask[..., None].bool(), 0.0)
if self.config.pooling == "average":
emb = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
elif self.config.pooling == "cls":
emb = last_hidden[:, 0]
if normalize:
emb = torch.nn.functional.normalize(emb, dim=-1)
return emb
def load_retriever(model_path, pooling="average", random_init=False):
# try: check if model exists locally
path = os.path.join(model_path, "checkpoint.pth")
if os.path.exists(path):
pretrained_dict = torch.load(path, map_location="cpu")
opt = pretrained_dict["opt"]
if hasattr(opt, "retriever_model_id"):
retriever_model_id = opt.retriever_model_id
else:
# retriever_model_id = "bert-base-uncased"
retriever_model_id = "bert-base-multilingual-cased"
tokenizer = utils.load_hf(transformers.AutoTokenizer, retriever_model_id)
cfg = utils.load_hf(transformers.AutoConfig, retriever_model_id)
if "xlm" in retriever_model_id:
model_class = XLMRetriever
else:
model_class = Contriever
retriever = model_class(cfg)
pretrained_dict = pretrained_dict["model"]
if any("encoder_q." in key for key in pretrained_dict.keys()): # test if model is defined with moco class
pretrained_dict = {k.replace("encoder_q.", ""): v for k, v in pretrained_dict.items() if "encoder_q." in k}
elif any("encoder." in key for key in pretrained_dict.keys()): # test if model is defined with inbatch class
pretrained_dict = {k.replace("encoder.", ""): v for k, v in pretrained_dict.items() if "encoder." in k}
retriever.load_state_dict(pretrained_dict, strict=False)
else:
retriever_model_id = model_path
if "xlm" in retriever_model_id:
model_class = XLMRetriever
else:
model_class = Contriever
cfg = utils.load_hf(transformers.AutoConfig, model_path)
tokenizer = utils.load_hf(transformers.AutoTokenizer, model_path)
retriever = utils.load_hf(model_class, model_path)
return retriever, tokenizer, retriever_model_id | null |
153,359 | import argparse
import numpy as np
from tqdm import tqdm
import argparse
from vllm import LLM, SamplingParams
from utils import load_file, TASK_INST, PROMPT_DICT, save_file_jsonl, process_arc_instruction, postprocess_answers_closed
from metrics import metric_max_over_ground_truths, exact_match_score, match
import ast
import backoff
import openai
from openai.error import APIError, Timeout, APIConnectionError
def completions_with_backoff(**kwargs):
return openai.ChatCompletion.create(**kwargs)
def call_model_chatgpt(prompt, model, max_tokens=50):
print(model)
try:
results = completions_with_backoff(
model=model,
messages=[
{"role": "user",
"content": prompt},
],
request_timeout=60,
max_tokens=max_tokens,
)
result = results["choices"][0]["message"]["content"]
except (APIError, Timeout, APIConnectionError):
result = "ERROR: API error outputs"
return result | null |
153,360 | import argparse
import numpy as np
from tqdm import tqdm
import argparse
from vllm import LLM, SamplingParams
from utils import load_file, TASK_INST, PROMPT_DICT, save_file_jsonl, process_arc_instruction, postprocess_answers_closed
from metrics import metric_max_over_ground_truths, exact_match_score, match
import ast
import backoff
import openai
from openai.error import APIError, Timeout, APIConnectionError
def completions_instructgpt_backoff(**kwargs):
return openai.Completion.create(**kwargs)
def call_model_instructgpt(prompt, model, max_tokens=50):
try:
results = completions_instructgpt_backoff(model=model, prompt=prompt, temperature=0.0,
max_tokens=max_tokens, logprobs=5, top_p=1, frequency_penalty=0.0, presence_penalty=0.0)
result = results["choices"][0]["text"]
except (APIError, Timeout, APIConnectionError):
results = "ERROR: API error outputs"
return result | null |
153,361 | import argparse
import numpy as np
from tqdm import tqdm
import argparse
from vllm import LLM, SamplingParams
from utils import load_file, TASK_INST, PROMPT_DICT, save_file_jsonl, process_arc_instruction, postprocess_answers_closed
from metrics import metric_max_over_ground_truths, exact_match_score, match
import ast
import backoff
import openai
from openai.error import APIError, Timeout, APIConnectionError
def postprocess_output(pred):
pred = pred.replace("</s>", "")
if len(pred) > 0 and pred[0] == " ":
pred = pred[1:]
return pred
def call_model(prompts, model, max_new_tokens=50):
sampling_params = SamplingParams(
temperature=0.8, top_p=0.95, max_tokens=max_new_tokens)
preds = model.generate(prompts, sampling_params)
preds = [pred.outputs[0].text.split("\n\n")[0] for pred in preds]
postprocessed_preds = [postprocess_output(pred) for pred in preds]
return postprocessed_preds, preds | null |
153,362 | import argparse
import logging
import math
import os
import random
import datasets
import torch
import copy
from functools import partial
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from typing import Optional, Dict, Sequence
import json
import transformers
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
LlamaTokenizer,
LlamaTokenizerFast,
SchedulerType,
DataCollatorForSeq2Seq,
get_scheduler,
GPTNeoXTokenizerFast,
GPT2Tokenizer,
OPTForCausalLM
)
from peft import LoraConfig, TaskType, get_peft_model
def parse_args():
parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
parser.add_argument(
"--dataset_name",
type=str,
default=None,
help="The name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--dataset_config_name",
type=str,
default=None,
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--train_file", type=str, default=None, help="A csv or a json file containing the training data."
)
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to pretrained model or model identifier from huggingface.co/models.",
required=False,
)
parser.add_argument(
"--config_name",
type=str,
default=None,
help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--use_lora",
action="store_true",
help="If passed, will use LORA (low-rank parameter-efficient training) to train the model.",
)
parser.add_argument(
"--lora_rank",
type=int,
default=64,
help="The rank of lora.",
)
parser.add_argument(
"--lora_alpha",
type=float,
default=16,
help="The alpha parameter of lora.",
)
parser.add_argument(
"--lora_dropout",
type=float,
default=0.1,
help="The dropout rate of lora modules.",
)
parser.add_argument(
"--save_merged_lora_model",
action="store_true",
help="If passed, will merge the lora modules and save the entire model.",
)
parser.add_argument(
"--use_flash_attn",
action="store_true",
help="If passed, will use flash attention to train the model.",
)
parser.add_argument(
"--tokenizer_name",
type=str,
default=None,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--use_slow_tokenizer",
action="store_true",
help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
)
parser.add_argument(
"--max_seq_length",
type=int,
default=512,
help="The maximum total sequence length (prompt+completion) of each training example.",
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=8,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=5e-5,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
parser.add_argument(
"--max_train_steps",
type=int,
default=None,
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--lr_scheduler_type",
type=SchedulerType,
default="linear",
help="The scheduler type to use.",
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
)
parser.add_argument(
"--warmup_ratio", type=float, default=0, help="Ratio of total training steps used for warmup."
)
parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=None,
help="The number of processes to use for the preprocessing.",
)
parser.add_argument(
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
)
parser.add_argument(
"--checkpointing_steps",
type=str,
default=None,
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
)
parser.add_argument(
"--logging_steps",
type=int,
default=None,
help="Log the training loss and learning rate every logging_steps steps.",
)
parser.add_argument(
"--resume_from_checkpoint",
type=str,
default=None,
help="If the training should continue from a checkpoint folder.",
)
parser.add_argument(
"--with_tracking",
action="store_true",
help="Whether to enable experiment trackers for logging.",
)
parser.add_argument(
"--report_to",
type=str,
default="all",
help=(
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
' `"wandb"`, `"comet_ml"` and `"clearml"`. Use `"all"` (default) to report to all integrations.'
"Only applicable when `--with_tracking` is passed."
),
)
parser.add_argument(
"--low_cpu_mem_usage",
action="store_true",
help=(
"It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded."
"If passed, LLM loading time and RAM consumption will be benefited."
),
)
parser.add_argument(
"--use_special_tokens",
action="store_true",
help=(
"Use special tokens."
),
)
args = parser.parse_args()
# Sanity checks
if args.dataset_name is None and args.train_file is None:
raise ValueError("Need either a dataset name or a training file.")
else:
if args.train_file is not None:
extension = args.train_file.split(".")[-1]
assert extension in ["json", "jsonl"], "`train_file` should be a json/jsonl file."
return args | null |
153,363 | import argparse
import logging
import math
import os
import random
import datasets
import torch
import copy
from functools import partial
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from typing import Optional, Dict, Sequence
import json
import transformers
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
LlamaTokenizer,
LlamaTokenizerFast,
SchedulerType,
DataCollatorForSeq2Seq,
get_scheduler,
GPTNeoXTokenizerFast,
GPT2Tokenizer,
OPTForCausalLM
)
from peft import LoraConfig, TaskType, get_peft_model
PROMPT_DICT = {
"prompt_input": (
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n"
),
"prompt_no_input": (
"### Instruction:\n{instruction}\n\n### Response:\n"
),
}
def _tokenize_fn(text: str, tokenizer: transformers.PreTrainedTokenizer, max_seq_length: int) -> Dict:
"""Tokenize a list of strings."""
input_ids = labels = tokenizer(
text,
return_tensors="pt",
padding="longest",
max_length=max_seq_length,
truncation=True,
).input_ids
input_ids_lens = labels_lens = input_ids.ne(tokenizer.pad_token_id).sum().item()
print(input_ids_lens)
return dict(
input_ids=input_ids,
labels=labels,
input_ids_lens=input_ids_lens,
labels_lens=labels_lens,
)
The provided code snippet includes necessary dependencies for implementing the `encode_with_prompt_completion_format` function. Write a Python function `def encode_with_prompt_completion_format(example, tokenizer, max_seq_length, context_markups=None)` to solve the following problem:
Here we assume each example has 'prompt' and 'completion' fields. We concatenate prompt and completion and tokenize them together because otherwise prompt will be padded/trancated and it doesn't make sense to follow directly with the completion.
Here is the function:
def encode_with_prompt_completion_format(example, tokenizer, max_seq_length, context_markups=None):
'''
Here we assume each example has 'prompt' and 'completion' fields.
We concatenate prompt and completion and tokenize them together because otherwise prompt will be padded/trancated
and it doesn't make sense to follow directly with the completion.
'''
# if prompt doesn't end with space and completion doesn't start with space, add space
prompt_input, prompt_no_input = PROMPT_DICT["prompt_input"], PROMPT_DICT["prompt_no_input"]
source_text = prompt_input.format_map(example) if example.get("input", "") != "" else prompt_no_input.format_map(example)
target_text = example['output'] + tokenizer.eos_token
examples_tokenized = _tokenize_fn(source_text + target_text, tokenizer, max_seq_length)
sources_tokenized = _tokenize_fn(source_text, tokenizer, max_seq_length)
input_ids = examples_tokenized["input_ids"].flatten()
source_len = sources_tokenized["input_ids_lens"]
labels = copy.deepcopy(input_ids)
labels[ :source_len-1] = -100
if context_markups is not None:
context_start = False
for j, orig_token in enumerate(labels[source_len:]):
if context_start is False and orig_token == context_markups[0]:
context_start = True
assert labels[source_len+j] == context_markups[0]
start_idx = j+source_len
end_idx = None
for k, orig_token_2 in enumerate(labels[start_idx:]):
if orig_token_2 == context_markups[1]:
end_idx = start_idx + k
if end_idx is None:
end_idx = start_idx + k
else:
assert labels[end_idx] == context_markups[1]
labels[start_idx+1:end_idx] = -100
context_start = False
attention_mask = torch.ones_like(input_ids)
return {
'input_ids': input_ids.flatten(),
'labels': labels.flatten(),
'attention_mask': attention_mask.flatten()
} | Here we assume each example has 'prompt' and 'completion' fields. We concatenate prompt and completion and tokenize them together because otherwise prompt will be padded/trancated and it doesn't make sense to follow directly with the completion. |
153,364 | import argparse
import logging
import math
import os
import random
import datasets
import torch
import copy
from functools import partial
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from typing import Optional, Dict, Sequence
import json
import transformers
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
LlamaTokenizer,
LlamaTokenizerFast,
SchedulerType,
DataCollatorForSeq2Seq,
get_scheduler,
GPTNeoXTokenizerFast,
GPT2Tokenizer,
OPTForCausalLM
)
from peft import LoraConfig, TaskType, get_peft_model
The provided code snippet includes necessary dependencies for implementing the `encode_with_messages_format` function. Write a Python function `def encode_with_messages_format(example, tokenizer, max_seq_length)` to solve the following problem:
Here we assume each example has a 'messages' field Each message is a dict with 'role' and 'content' fields. We concatenate all messages with the roles as delimiters and tokenize them together.
Here is the function:
def encode_with_messages_format(example, tokenizer, max_seq_length):
'''
Here we assume each example has a 'messages' field Each message is a dict with 'role' and 'content' fields.
We concatenate all messages with the roles as delimiters and tokenize them together.
'''
messages = example['messages']
if len(messages) == 0:
raise ValueError('messages field is empty.')
def _concat_messages(messages):
message_text = ""
for message in messages:
if message["role"] == "system":
message_text += "<|system|>\n" + message["content"].strip() + "\n"
elif message["role"] == "user":
message_text += "<|user|>\n" + message["content"].strip() + "\n"
elif message["role"] == "assistant":
message_text += "<|assistant|>\n" + message["content"].strip() + tokenizer.eos_token + "\n"
else:
raise ValueError("Invalid role: {}".format(message["role"]))
return message_text
example_text = _concat_messages(messages).strip()
tokenized_example = tokenizer(example_text, return_tensors='pt', max_length=max_seq_length, truncation=True)
input_ids = tokenized_example.input_ids
labels = input_ids.clone()
# mask the non-assistant part for avoiding loss
for message_idx, message in enumerate(messages):
if message["role"] != "assistant":
if message_idx == 0:
message_start_idx = 0
else:
message_start_idx = tokenizer(
_concat_messages(messages[:message_idx]), return_tensors='pt', max_length=max_seq_length, truncation=True
).input_ids.shape[1]
if message_idx < len(messages) - 1 and messages[message_idx+1]["role"] == "assistant":
# here we also ignore the role of the assistant
messages_so_far = _concat_messages(messages[:message_idx+1]) + "<|assistant|>\n"
else:
messages_so_far = _concat_messages(messages[:message_idx+1])
message_end_idx = tokenizer(
messages_so_far,
return_tensors='pt',
max_length=max_seq_length,
truncation=True
).input_ids.shape[1]
labels[:, message_start_idx:message_end_idx] = -100
if message_end_idx >= max_seq_length:
break
attention_mask = torch.ones_like(input_ids)
return {
'input_ids': input_ids.flatten(),
'labels': labels.flatten(),
'attention_mask': attention_mask.flatten(),
} | Here we assume each example has a 'messages' field Each message is a dict with 'role' and 'content' fields. We concatenate all messages with the roles as delimiters and tokenize them together. |
153,365 | import os
import argparse
import csv
import logging
import pickle
import numpy as np
import torch
import transformers
import src.slurm
import src.contriever
import src.utils
import src.data
import src.normalize_text
def embed_passages(args, passages, model, tokenizer):
total = 0
allids, allembeddings = [], []
batch_ids, batch_text = [], []
with torch.no_grad():
for k, p in enumerate(passages):
batch_ids.append(p["id"])
if args.no_title or not "title" in p:
text = p["text"]
else:
text = p["title"] + " " + p["text"]
if args.lowercase:
text = text.lower()
if args.normalize_text:
text = src.normalize_text.normalize(text)
batch_text.append(text)
if len(batch_text) == args.per_gpu_batch_size or k == len(passages) - 1:
encoded_batch = tokenizer.batch_encode_plus(
batch_text,
return_tensors="pt",
max_length=args.passage_maxlength,
padding=True,
truncation=True,
)
encoded_batch = {k: v.cuda() for k, v in encoded_batch.items()}
embeddings = model(**encoded_batch)
embeddings = embeddings.cpu()
total += len(batch_ids)
allids.extend(batch_ids)
allembeddings.append(embeddings)
batch_text = []
batch_ids = []
if k % 100000 == 0 and k > 0:
print(f"Encoded passages {total}")
allembeddings = torch.cat(allembeddings, dim=0).numpy()
return allids, allembeddings | null |
153,366 | import os
import argparse
import json
import pickle
import time
import glob
from pathlib import Path
import numpy as np
import torch
import transformers
import src.index
import src.contriever
import src.utils
import src.slurm
import src.data
from src.evaluation import calculate_matches
import src.normalize_text
def add_hasanswer(data, hasanswer):
# add hasanswer to data
for i, ex in enumerate(data):
for k, d in enumerate(ex["ctxs"]):
d["hasanswer"] = hasanswer[i][k] | null |
153,367 | import os
import argparse
import json
import pickle
import time
import glob
from pathlib import Path
import numpy as np
import torch
import transformers
import src.index
import src.contriever
import src.utils
import src.slurm
import src.data
from src.evaluation import calculate_matches
import src.normalize_text
def load_data(data_path):
if data_path.endswith(".json"):
with open(data_path, "r") as fin:
data = json.load(fin)
elif data_path.endswith(".jsonl"):
data = []
with open(data_path, "r") as fin:
for k, example in enumerate(fin):
example = json.loads(example)
data.append(example)
return data | null |
153,368 | import argparse
import jsonlines
from transformers import AutoTokenizer
import numpy as np
import json
import argparse
from vllm import LLM, SamplingParams
from utils import TASK_INST, PROMPT_DICT, load_special_tokens, load_jsonlines, postprocess, fix_spacing
def run_step_generation_batch(model, prompt, paragraphs, max_new_tokens,
rel_tokens=None, grd_tokens=None, ret_tokens=None, ut_tokens=None,
threshold=None, w_rel=1.0, w_sup=1.0, w_use=0.5, use_seqscore=False):
if paragraphs is not None:
aug_prompts = [prompt + "[Retrieval]" + "<paragraph>{}</paragraph>".format(
paragraph["title"] + "\n" + paragraph["text"]) for paragraph in paragraphs]
else:
aug_prompts = [prompt]
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, max_tokens=max_new_tokens, logprobs=32000, )
preds = model.generate(aug_prompts, sampling_params)
# compute the scores for each generation
relevance_score_dict = {}
grd_score_dict = {}
ut_score_dict = {}
overall_scores = {}
final_preds = []
for p_idx, pred in enumerate(preds):
pred_token_ids = pred.outputs[0].token_ids
pred_text = pred.outputs[0].text
pred_log_probs = pred.outputs[0].logprobs
seq_score = pred.outputs[0].cumulative_logprob / \
max(len(pred.outputs[0].token_ids), 1)
assert len(pred_log_probs) == len(pred_token_ids)
relevance_score_dict.setdefault(p_idx, {})
grd_score_dict.setdefault(p_idx, {})
ut_score_dict.setdefault(p_idx, {})
# Compute reward scores
for tok, id in rel_tokens.items():
if id not in pred_log_probs[0]:
prob = -100
else:
prob = np.exp(pred_log_probs[0][id])
relevance_score_dict[p_idx][tok] = prob
if grd_tokens is not None:
groundness_token_appear_indices = []
for tok_idx, tok in enumerate(pred_token_ids):
if tok in list(grd_tokens.values()):
groundness_token_appear_indices.append(tok_idx)
break
if len(groundness_token_appear_indices) > 0:
idx = groundness_token_appear_indices[0]
for token, token_id in grd_tokens.items():
prob = pred_log_probs[idx][token_id] if token_id in pred_log_probs[idx] else -100
grd_score_dict[p_idx][token] = np.exp(prob)
utility_token_appear_indices = []
if ut_tokens is not None:
for tok_idx, tok in enumerate(pred_token_ids):
if tok in list(ut_tokens.values()):
utility_token_appear_indices.append(tok_idx)
if len(utility_token_appear_indices) > 0:
idx = utility_token_appear_indices[0]
for token, token_id in grd_tokens.items():
prob = pred_log_probs[idx][token_id] if token_id in pred_log_probs[idx] else -100
ut_score_dict[p_idx][token] = np.exp(prob)
relevance_score = relevance_score_dict[p_idx]["[Relevant]"] / (
np.sum(list(relevance_score_dict[p_idx].values())))
if len(grd_score_dict[p_idx]) == 3:
gt_sum = np.sum(list(grd_score_dict[p_idx].values()))
ground_score = (grd_score_dict[p_idx]["[Fully supported]"] / gt_sum) + 0.5 * (
grd_score_dict[p_idx]["[Partially supported]"] / gt_sum)
else:
ground_score = 0.0
if len(ut_score_dict[p_idx]) == 5:
ut_sum = np.sum(list(ut_score_dict[p_idx].values()))
ut_scores = [-1, -0.5, 0, 0.5, 1]
utility_score = np.sum([ut_scores[i] * (ut_score_dict[p_idx]["[Utility:{}]".format(i+1)] / ut_sum)
if "[Utility:{}]".format(i+1) in ut_score_dict[p_idx] else 0.0 for i in range(0, 5)])
else:
utility_score = 0.0
if use_seqscore is True:
final_score =np.exp(seq_score) + w_rel * relevance_score + \
w_sup * ground_score + w_use * utility_score
else:
final_score = w_rel * relevance_score + \
w_sup * ground_score + w_use * utility_score
overall_scores[p_idx] = {"final_score": final_score,
"relevance_score": relevance_score,
"ground_score": ground_score,
"utility_score": utility_score,
"relevance_score_dict": relevance_score_dict,
"grd_score_dict": grd_score_dict,
"ut_score_dict": utility_score}
# modify and add do retrieve tokens
if "[No Retrieval]" in pred_text:
ret_token_appear_indices = []
substrings = pred_text.split("[No Retrieval]")
for tok_idx, tok in enumerate(pred_token_ids):
if tok == ret_tokens["[No Retrieval]"]:
ret_token_appear_indices.append(tok_idx)
substrings
print("retrieval_tokens")
ret_token_score_dict = {}
retrieval_remap = {}
for order, idx in enumerate(ret_token_appear_indices):
ret_token_score_dict.setdefault(order, {})
for tok, tok_id in ret_tokens.items():
prob = pred_log_probs[idx][tok_id] if tok_id in pred_log_probs[idx] else -100
ret_token_score_dict[order][tok] = np.exp(prob)
if ret_token_score_dict[order]["[Retrieval]"] + ret_token_score_dict[order]["[No Retrieval]"] != 0.0:
do_retrieve = (ret_token_score_dict[order]["[Retrieval]"] + ret_token_score_dict[order]["[Continue to Use Evidence]"]) / (
ret_token_score_dict[order]["[Retrieval]"] + ret_token_score_dict[order]["[No Retrieval]"]) > threshold
else:
do_retrieve = 0.0
if do_retrieve > threshold:
retrieval_remap[order] = True
else:
retrieval_remap[order] = False
processed_pred = ""
for substr_i, substring in enumerate(substrings):
if substr_i in retrieval_remap and retrieval_remap[substr_i] is True:
processed_pred += substring + "[Retrieval]"
else:
processed_pred += substring + "[No Retrieval]"
pred_text = processed_pred
final_preds.append(pred_text)
else:
final_preds.append(pred_text)
preds = final_preds
scores = [overall_scores[p_idx]["final_score"] for p_idx in overall_scores]
return preds, scores, overall_scores
def call_model_beam_batch(prompt, model, max_new_tokens=15, ctxs=None, query=None, max_depth=5, rel_tokens=None,
grd_tokens=None, ret_tokens=None, threshold=None, beam_width=2, ut_tokens=None, use_seqscore=False,
w_rel=1.0, w_sup=1.0, w_use=0.5, ignore_cont=False, mode="adaptive_retrieval"):
special_tokens = []
if "## Input:\n\n" in query:
query = query.split("## Input:\n\n")[1]
if rel_tokens is not None:
special_tokens = list(rel_tokens.keys())
if ret_tokens is not None:
special_tokens += list(ret_tokens.keys())
if mode == "no_retrieval":
sampling_params = SamplingParams(
temperature=0.0, top_p=1, max_tokens=max_new_tokens)
prompt += "[No Retrieval]"
preds = model.generate([prompt], sampling_params)
preds = [pred.outputs[0].text.split("\n\n")[0] for pred in preds]
return preds[0], prediction_tree
do_retrieve = False
if mode == "always_retrieve":
do_retrieve = True
else:
sampling_params = SamplingParams(
temperature=0.0, top_p=1, max_tokens=25, logprobs=32000)
preds = model.generate([prompt], sampling_params)
pred_log_probs = preds[0].outputs[0].logprobs
preds = [pred.outputs[0].text.split("\n\n")[0] for pred in preds]
if "[Retrieval]" not in preds[0]:
do_retrieve = False
else:
if threshold is None:
do_retrieve = False
else:
ret_token_score_dict = {}
for tok, tok_id in ret_tokens.items():
prob = pred_log_probs[0][tok_id]
ret_token_score_dict[tok] = np.exp(prob)
retrieve_prob = ret_token_score_dict["[Retrieval]"] / (
ret_token_score_dict["[Retrieval]"] + ret_token_score_dict["[No Retrieval]"])
do_retrieve = True if retrieve_prob > threshold else False
if do_retrieve is False:
sampling_params = SamplingParams(
temperature=0.0, top_p=1, max_tokens=max_new_tokens)
prompt += "[No Retrieval]"
preds = model.generate([prompt], sampling_params)
preds = [pred.outputs[0].text.split("\n\n")[0] for pred in preds]
prediction_tree = {}
return preds[0], prediction_tree
elif do_retrieve is True:
curr_depth = 1
terminated = False
node_id = 0
prediction_tree = {}
levels = {}
prediction_tree[node_id] = {"prompt": prompt, "pred": "[Retrieval]",
"processed_pred": "", "score": None, "ctx": None, "parent": None}
levels[0] = [0]
while curr_depth < max_depth:
levels[curr_depth] = []
if curr_depth-1 in levels and terminated is False:
for node in levels[curr_depth-1]:
pred = prediction_tree[node]["pred"]
if pred == "</s>":
terminated = True
continue
prompt = prediction_tree[node]["prompt"]
prev_generation = prediction_tree[node]["processed_pred"]
score = prediction_tree[node]["score"]
if "[Retrieval]" in pred:
retrieval_results = {}
preds, scores, overall_score_dict = run_step_generation_batch(
model, prompt + prev_generation, ctxs, max_new_tokens,
rel_tokens, ret_tokens=ret_tokens, grd_tokens=grd_tokens, ut_tokens=ut_tokens,
threshold=threshold, w_rel=w_rel, w_sup=w_sup, w_use=w_use)
for i, (pred, p_score) in enumerate(zip(preds, scores)):
retrieval_results[i] = {
"pred": pred, "score": p_score}
for i, result in retrieval_results.items():
node_id += 1
node_score = result["score"] * \
score if score is not None else result["score"]
pred = result["pred"]
prediction_tree[node_id] = {"prompt": prompt + prev_generation, "pred": pred,
"score": node_score, "ctx": ctxs[i], "parent": node,
"overall_score_dict": overall_score_dict}
if "[Retrieval]" in pred:
gen_result_index = pred.index("[Retrieval]")
prev_generation = pred[:gen_result_index]
else:
prev_generation = pred
prediction_tree[node_id]["processed_pred"] = prev_generation
levels[curr_depth].append(node_id)
current_rank = levels[curr_depth]
node2score = {
node_id: prediction_tree[node_id]["score"] for node_id in current_rank}
top_nodes = sorted(node2score.items(), key=lambda x: x[1], reverse=True)[
:beam_width]
levels[curr_depth] = [node[0] for node in top_nodes]
curr_depth += 1
else:
break
final_prediction = ""
parent = 0
best_selections = {}
# Traverse from the bottom
levels = {k: v for k, v in levels.items() if len(v) > 0 and k != 0}
for path_i, node in enumerate(levels[len(levels)]):
if node == 0:
break
best_selections[path_i] = [node]
current_node = node
current_level = curr_depth
if current_node is None:
continue
while current_level > 0 and current_node is not None:
parent = prediction_tree[current_node]["parent"]
best_selections[path_i] = [parent] + best_selections[path_i]
current_node = parent
current_level += 1
final_prediction = {}
splitted_sentences = {}
original_splitted_sentences = {}
ctxs = {}
for path_i, nodes in best_selections.items():
final_prediction[path_i] = " ".join([prediction_tree[node]["processed_pred"] for node in nodes if node is not None and (
ignore_cont is False or (ignore_cont is True and "[No support / Contradictory]" not in prediction_tree[node]["processed_pred"]))])
splitted_sentences[path_i] = [prediction_tree[node]["processed_pred"] for node in nodes if node is not None and (
ignore_cont is False or (ignore_cont is True and "[No support / Contradictory]" not in prediction_tree[node]["processed_pred"]))]
original_splitted_sentences[path_i] = [prediction_tree[node]["pred"] for node in nodes if node is not None and (
ignore_cont is False or (ignore_cont is True and "[No support / Contradictory]" not in prediction_tree[node]["processed_pred"]))]
ctxs[path_i] = [prediction_tree[node]["ctx"] for node in nodes if node is not None and (ignore_cont is False or (
ignore_cont is True and "[No support / Contradictory]" not in prediction_tree[node]["processed_pred"]))]
result = {"final_prediction": final_prediction,
"splitted_sentences": splitted_sentences,
"original_splitted_sentences": original_splitted_sentences,
"best_selections": best_selections,
"ctxs": ctxs,
"prediction_tree": prediction_tree}
return final_prediction, result | null |
153,369 | import numpy as np
import string
import re
from collections import Counter
import re
def normalize_answer(s):
def exact_match_score(prediction, ground_truth):
return (normalize_answer(prediction) == normalize_answer(ground_truth)) | null |
153,370 | import numpy as np
import string
import re
from collections import Counter
import re
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = metric_fn(prediction, ground_truth)
scores_for_ground_truths.append(score)
return max(scores_for_ground_truths) | null |
153,371 | import numpy as np
import string
import re
from collections import Counter
import re
def accuracy(preds, labels):
match_count = 0
for pred, label in zip(preds, labels):
target = label[0]
if pred == target:
match_count += 1
return 100 * (match_count / len(preds)) | null |
153,372 | import numpy as np
import string
import re
from collections import Counter
import re
def find_entity_tags(sentence):
entity_regex = r'(.+?)(?=\s<|$)'
tag_regex = r'<(.+?)>'
entity_names = re.findall(entity_regex, sentence)
tags = re.findall(tag_regex, sentence)
results = {}
for entity, tag in zip(entity_names, tags):
if "<" in entity:
results[entity.split("> ")[1]] = tag
else:
results[entity] = tag
return results | null |
153,373 | import numpy as np
import string
import re
from collections import Counter
import re
def match(prediction, ground_truth):
for gt in ground_truth:
if gt in prediction:
return 1
return 0 | null |
153,374 | from __future__ import print_function
import datetime
import time
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
import codecs
import pickle
import math
from model_word_ada.LM import LM
from model_word_ada.basic import BasicRNN
from model_word_ada.ddnet import DDRNN
from model_word_ada.radam import RAdam
from model_word_ada.ldnet import LDRNN
from model_word_ada.densenet import DenseRNN
from model_word_ada.dataset import LargeDataset, EvalDataset
from model_word_ada.adaptive import AdaptiveSoftmax
import model_word_ada.utils as utils
import argparse
import json
import os
import sys
import itertools
import functools
def evaluate(data_loader, lm_model, criterion, limited = 76800):
print('evaluating')
lm_model.eval()
iterator = data_loader.get_tqdm()
lm_model.init_hidden()
total_loss = 0
total_len = 0
for word_t, label_t in iterator:
label_t = label_t.view(-1)
tmp_len = label_t.size(0)
output = lm_model.log_prob(word_t)
total_loss += tmp_len * utils.to_scalar(criterion(autograd.Variable(output), label_t))
total_len += tmp_len
if limited >=0 and total_len > limited:
break
ppl = math.exp(total_loss / total_len)
print('PPL: ' + str(ppl))
return ppl | null |
153,375 | import pickle
import argparse
import os
import codecs
import random
import numpy as np
from tqdm import tqdm
import itertools
import functools
def encode_dataset(input_folder, w_map, reverse):
w_eof = w_map['\n']
w_unk = w_map['<unk>']
list_dirs = os.walk(input_folder)
lines = list()
for root, dirs, files in list_dirs:
for file in tqdm(files):
with codecs.open(os.path.join(root, file), 'r', 'utf-8') as fin:
lines = lines + list(filter(lambda t: t and not t.isspace(), fin.readlines()))
dataset = list()
for line in lines:
dataset += list(map(lambda t: w_map.get(t, w_unk), line.split())) + [w_eof]
if reverse:
dataset = dataset[::-1]
return dataset | null |
153,376 | import pickle
import argparse
import os
import codecs
import random
import numpy as np
from tqdm import tqdm
import itertools
import functools
def encode_dataset2file(input_folder, output_folder, w_map, reverse):
w_eof = w_map['\n']
w_unk = w_map['<unk>']
list_dirs = os.walk(input_folder)
range_ind = 0
for root, dirs, files in list_dirs:
for file in tqdm(files):
with codecs.open(os.path.join(root, file), 'r', 'utf-8') as fin:
lines = list(filter(lambda t: t and not t.isspace(), fin.readlines()))
dataset = list()
for line in lines:
dataset += list(map(lambda t: w_map.get(t, w_unk), line.split())) + [w_eof]
if reverse:
dataset = dataset[::-1]
with open(output_folder+'train_'+ str(range_ind) + '.pk', 'wb') as f:
pickle.dump(dataset, f)
range_ind += 1
return range_ind | null |
153,377 | import numpy as np
import torch
import json
import torch
import torch.nn as nn
import torch.nn.init
from torch.autograd import Variable
The provided code snippet includes necessary dependencies for implementing the `repackage_hidden` function. Write a Python function `def repackage_hidden(h)` to solve the following problem:
Wraps hidden states in new Variables, to detach them from their history.
Here is the function:
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if type(h) == torch.Tensor:
return h.data
else:
return tuple(repackage_hidden(v) for v in h) | Wraps hidden states in new Variables, to detach them from their history. |
153,378 | import numpy as np
import torch
import json
import torch
import torch.nn as nn
import torch.nn.init
from torch.autograd import Variable
The provided code snippet includes necessary dependencies for implementing the `init_embedding` function. Write a Python function `def init_embedding(input_embedding)` to solve the following problem:
Initialize embedding
Here is the function:
def init_embedding(input_embedding):
"""
Initialize embedding
"""
bias = np.sqrt(3.0 / input_embedding.size(1))
nn.init.uniform(input_embedding, -bias, bias) | Initialize embedding |
153,379 | import numpy as np
import torch
import json
import torch
import torch.nn as nn
import torch.nn.init
from torch.autograd import Variable
The provided code snippet includes necessary dependencies for implementing the `init_linear` function. Write a Python function `def init_linear(input_linear)` to solve the following problem:
Initialize linear transformation
Here is the function:
def init_linear(input_linear):
"""
Initialize linear transformation
"""
bias = np.sqrt(6.0 / (input_linear.weight.size(0) + input_linear.weight.size(1)))
nn.init.uniform(input_linear.weight, -bias, bias)
if input_linear.bias is not None:
input_linear.bias.data.zero_() | Initialize linear transformation |
153,380 | import numpy as np
import torch
import json
import torch
import torch.nn as nn
import torch.nn.init
from torch.autograd import Variable
The provided code snippet includes necessary dependencies for implementing the `adjust_learning_rate` function. Write a Python function `def adjust_learning_rate(optimizer, lr)` to solve the following problem:
shrink learning rate for pytorch
Here is the function:
def adjust_learning_rate(optimizer, lr):
"""
shrink learning rate for pytorch
"""
for param_group in optimizer.param_groups:
param_group['lr'] = lr | shrink learning rate for pytorch |
153,381 | import numpy as np
import torch
import json
import torch
import torch.nn as nn
import torch.nn.init
from torch.autograd import Variable
The provided code snippet includes necessary dependencies for implementing the `init_lstm` function. Write a Python function `def init_lstm(input_lstm)` to solve the following problem:
Initialize lstm
Here is the function:
def init_lstm(input_lstm):
"""
Initialize lstm
"""
for ind in range(0, input_lstm.num_layers):
weight = eval('input_lstm.weight_ih_l'+str(ind))
bias = np.sqrt(6.0 / (weight.size(0)/4 + weight.size(1)))
nn.init.uniform(weight, -bias, bias)
weight = eval('input_lstm.weight_hh_l'+str(ind))
bias = np.sqrt(6.0 / (weight.size(0)/4 + weight.size(1)))
nn.init.uniform(weight, -bias, bias)
if input_lstm.bias:
for ind in range(0, input_lstm.num_layers):
weight = eval('input_lstm.bias_ih_l'+str(ind))
weight.data.zero_()
weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1
weight = eval('input_lstm.bias_hh_l'+str(ind))
weight.data.zero_()
weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1 | Initialize lstm |
153,382 | from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import models.imagenet as customized_models
from utils import Bar, Logger, AverageMeter, accuracy, mkdir_p, savefig
from utils.radam import RAdam, AdamW
torch.manual_seed(args.manualSeed)
def train(train_loader, model, criterion, optimizer, epoch, use_cuda):
# switch to train mode
model.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
end = time.time()
bar = Bar('Processing', max=len(train_loader))
for batch_idx, (inputs, targets) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda(non_blocking=True)
inputs, targets = torch.autograd.Variable(inputs), torch.autograd.Variable(targets)
# compute output
outputs = model(inputs)
loss = criterion(outputs, targets)
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5))
losses.update(loss.data[0], inputs.size(0))
top1.update(prec1[0], inputs.size(0))
top5.update(prec5[0], inputs.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# plot progress
bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f} | top5: {top5: .4f}'.format(
batch=batch_idx + 1,
size=len(train_loader),
data=data_time.val,
bt=batch_time.val,
total=bar.elapsed_td,
eta=bar.eta_td,
loss=losses.avg,
top1=top1.avg,
top5=top5.avg,
)
bar.next()
bar.finish()
return (losses.avg, top1.avg) | null |
153,383 | from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import models.imagenet as customized_models
from utils import Bar, Logger, AverageMeter, accuracy, mkdir_p, savefig
from utils.radam import RAdam, AdamW
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
torch.manual_seed(args.manualSeed)
def save_checkpoint(state, is_best, checkpoint='checkpoint', filename='checkpoint.pth.tar'):
filepath = os.path.join(checkpoint, filename)
torch.save(state, filepath)
if is_best:
shutil.copyfile(filepath, os.path.join(checkpoint, 'model_best.pth.tar')) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.