with open("fine-tune/train_questions.txt", "w") as f:
for question in questions:
f.write(question + "\n")
생성한 질문을 저장한 train_questions.txt 파일을 확인해 보겠습니다.
!cat fine-tune/train_questions.txt
What factors could potentially impact NVIDIA's ability to accurately forecast demand for its products, and how might these factors affect the company's financial results?
어떤 조건에 따라 Restricted Stock Unit Award가 부여되는지 설명하시오.
어떤 조건을 충족해야만 Ten Percent Stockholder가 Incentive Stock Option을 받을 수 있는가요?
- What was the total comprehensive income for NVIDIA Corporation for the year ended January 29, 2023?
- What were the main components contributing to the changes in deferred revenue for NVIDIA during fiscal years 2023 and 2022?
어떤 조건들이 주어진 상황에서 Restricted Stock Units의 소유주가 주식을 판매하거나 이전해야 하는지 설명하십시오?
어떤 목적으로 데이터가 수집되고 처리되는지에 대한 정확한 이해가 필요한가요?
What factors, in addition to the Company's financial development, may impact the future value of NVIDIA's Common Stock according to the information provided in the SEC 10-K document?
어떻게 NVIDIA는 외환 환산을 다루고 있으며, 이로 인해 발생하는 손익이 현재까지 중요하지 않았다고 평가하고 있는가?
어떻게 중국의 데이터 처리 및 데이터 로컬라이제이션에 관한 법률이 NVIDIA의 비즈니스 활동에 어떤 영향을 미칠 수 있는가?
어떤 국가의 법률이 중요한 데이터의 이전을 규제하고 있으며, 이로 인해 NVIDIA의 비즁니스 운영에 부정적인 영향을 줄 수 있는 가능성이 있습니까?
- How much total cost has NVIDIA incurred for share repurchases since the inception of their program up to January 29, 2023?
어떤 국가로 이주할 경우, 회사가 법적 또는 행정적 이유로 해당 국가의 조건이 적용될 수 있다는 점을 이해하고 있습니까?
어떤 조치가 주주들에 의해 취해져야만 하며 서면 동의로 이루어질 수 없는 것인가요?
- What types of Awards are provided for in the NVIDIA Corporation Amended and Restated 2007 Equity Incentive Plan?
어떤 채널을 통해 NVIDIA가 주요 금융 정보를 투자자에게 공지하고 정보를 공개하는데 사용하는 것으로 언급되었습니까?
- How has NVIDIA supported its workforce during the COVID-19 pandemic in terms of health and safety measures?
어떤 요인들이 NVIDIA의 재무 상황에 영향을 미치고 있는 것으로 보이나요?
어떤 국가의 거주자는 Türkiye에서 일반 주식을 판매할 수 없으며, 이러한 규정을 준수해야 하는가?
What significant audit matter related to the valuation of inventories did PricewaterhouseCoopers LLP address in their report on NVIDIA's consolidated financial statements?
What was the total fair value of RSUs and PSUs during the fiscal year ended January 29, 2023, according to the NVIDIA SEC 10-K document?
어떤 조건하에 개인정보 수집 및 이용이 이루어지며, 이에 동의하지 않을 경우 어떤 결과가 발생하는가?
어떤 방법으로 NVIDIA가 Mellanox를 인수한 후에 발생한 비용을 처리하고 있는가?
What impact did inventory provisions have on NVIDIA's gross margin in fiscal year 2023 compared to fiscal year 2022?
What was the total amount returned to shareholders by NVIDIA in fiscal year 2023 through share repurchases and cash dividends?
What are the key components included in NVIDIA's Compute & Networking segment and Graphics segment as outlined in the segment information note?
어떤 날짜에 비상장주식을 보유한 비제휴자들에 의해 보유된 투표 주식의 시장 가치가 약 434.37억 달러로 추정되었습니까?
What was the aggregate market value of the voting stock held by non-affiliates of the registrant as of July 29, 2022, based on the closing sales price of the registrant's common stock reported by the Nasdaq Global Select Market?
어떤 요인들이 NVIDIA의 제품 수요에 영향을 미치고, 이로 인해 제품의 공급과 수요 사이에 불일치가 발생할 수 있는가?
- What factors contributed to the increase in research and development expenses for fiscal year 2023 according to the NVIDIA SEC 10-K document?
어떤 조치를 한국 거주자는 외화 계좌의 월간 잔고가 일정 금액을 초과할 때 취해야 하는가?
What factors contributed to the decrease in NVIDIA's effective tax rate in fiscal year 2023 compared to fiscal year 2022?
어떤 요인들이 NVIDIA의 수익률 및 재무 결과에 부정적인 영향을 미칠 수 있는가?
어떤 기준에 따라 Performance Goals가 설정되며, Performance Criteria는 어떻게 결정되는가?
어떤 조건이 "Performance Goals"을 결정하는 데 사용되는가?
어떤 조건하에 홍콩 거주자에게 부여된 Restricted Stock Units은 현금으로 지급되지 않으며, 주식으로만 지급되어야 하는가?
- What was the total aggregate principal amount of senior notes issued by NVIDIA in June 2021, March 2020, and September 2016, respectively?
어떤 항목에 따라서 관련 거래 및 이사 독립성에 대한 정보가 제공되며, 이 정보는 어디에서 찾을 수 있습니까?
어떤 조건 하에 참가자의 Option 또는 SAR가 즉시 종료되는가?
어떤 조건에서 참가자의 Continuous Service가 종료되면 Option 또는 SAR는 즉시 종료되며 참가자는 그 이후에 Option 또는 SAR를 행사할 수 없게 됩니까?
Eval Generation
이제 평가 데이터 세트를 만들기 위해 완전히 다른 문서 세트에 대한 질문을 생성해 보겠습니다.
ataset_generator = DatasetGenerator.from_documents(
documents[
50:
], # since we generated ~1 question for 40 documents, we can skip the first 40
question_gen_query=question_gen_query,
llm=gpt_35_llm,
)
with open("./fine-tune/eval_questions.txt", "w") as f:
for question in questions:
f.write(question + "\n")
!cat fine-tune/eval_questions.txt
어떻게 NVIDIA의 수요 예측이 잘못되었을 때 회사의 재무 결과에 부정적인 영향을 미칠 수 있는지 설명하십시오.
어떤 상황에서 Restricted Stock Unit Award가 부여되며, 해당 상황에서 어떤 조건이 적용되는가?
- What are the criteria for a Ten Percent Stockholder to be granted an Incentive Stock Option according to the provisions outlined in the NVIDIA SEC 10-K document?
What was the total comprehensive income for NVIDIA Corporation and its subsidiaries for the year ended January 29, 2023?
- What were the main components contributing to the changes in deferred revenue for NVIDIA during fiscal years 2023 and 2022?
어떤 조건 하에 Restricted Stock Units의 주식을 판매할 수 있는지에 대한 규정은 무엇인가요?
어떤 목적으로 회사, Schwab 및 기타 수신자들이 데이터를 전달, 보유, 사용 및 이전할 수 있는지에 대해 어떤 권한이 주어지나요?
What factors, other than the Company's financial development, may impact the future value of NVIDIA's Common Stock according to the information provided in the SEC 10-K document?
어떤 조건에서 NVIDIA는 잠재적인 손실에 대한 손실을 인식하고 어떻게 처리합니까?
어떻게 중국 법률이 데이터 처리 및 데이터 지역화에 관한 요구 사항을 규정하고 있으며, 이러한 요구 사항을 준수하는 데 어떤 영향을 미칠 수 있는가?
어떤 국가의 법률이 중요한 데이터의 이전을 규제하고 있으며, 이로 인해 NVIDIA의 비즈니스 운영에 부정적인 영향을 줄 수 있는 가능성이 있습니까?
What was the total cost of shares repurchased by NVIDIA during fiscal year 2023 and how many shares were repurchased in total?
어떤 국가로 이주할 경우, NVIDIA의 보상 조건은 어떻게 변화하게 되는가?
어떤 조치가 주주들에 의해 취해져야만 하며 서면 동의로 이루어질 수 없는 것인가요?
어떤 종류의 상장된 시장에서 주식 보상이 제공될 수 있습니까?
어떤 방법으로 NVIDIA는 주요 금융 정보를 투자자들에게 공지하고 있나요?
어떤 조치를 취하여 직원들이 재택근무를 할 때 지원받을 수 있었나요?
What impact did the termination of the Arm Share Purchase Agreement have on NVIDIA's financials in fiscal year 2023?
어떤 국가의 거주자는 Türkiye에서 일반 주식을 판매할 수 없으며, 이러한 규정을 준수해야 하는가요?
What significant judgments and considerations were involved in the valuation of inventories, specifically the provisions for excess or obsolete inventories and excess product purchase commitments, as outlined in the PricewaterhouseCoopers LLP report on NVIDIA's SEC 10-K document?
What is the total fair value of RSUs and PSUs as of their respective vesting dates for the years ended January 29, 2023, January 30, 2022, and January 31, 2021?
어떤 조건에서만 개인정보 처리가 이루어지고 있는가?
어떤 방법으로 NVIDIA가 Mellanox를 인수한 후에 발생한 비용을 처리하고 있는가?
What impact did inventory provisions have on NVIDIA's gross margin in fiscal year 2023 compared to fiscal year 2022?
What was the total amount returned to shareholders by NVIDIA in fiscal year 2023 through share repurchases and cash dividends?
- How does NVIDIA allocate costs or expenses between its Compute & Networking segment and Graphics segment?
What was the aggregate market value of the voting stock held by non-affiliates of NVIDIA Corporation as of July 29, 2022, based on the closing sales price of the common stock reported by the Nasdaq Global Select Market?
- What was the aggregate market value of the voting stock held by non-affiliates of the registrant as of July 29, 2022, based on the closing sales price of the registrant's common stock?
어떤 요소들이 NVIDIA의 제품 수요에 영향을 미치고, 이로 인해 제품의 공급과 수요 간 불일치가 발생할 수 있는가?
- What was the reason behind the significant increase in research and development expenses for fiscal year 2023 according to the information provided in the NVIDIA SEC 10-K document?
어떤 조치를 취해야 일본 거주자가 매년 3월 15일까지 외국 자산을 보고해야 하는지에 대해 설명해 주세요.
What factors contributed to the decrease in NVIDIA's effective tax rate in fiscal year 2023 compared to fiscal year 2022?
어떤 요인들이 NVIDIA의 수익률과 재무 결과에 부정적인 영향을 미칠 수 있는가?
어떤 기준에 따라 Performance Goals가 설정되며, Performance Criteria는 어떤 요소들을 기반으로 선택될 수 있는가?
What criteria does the Committee use to define Performance Goals for a Performance Period in the NVIDIA SEC 10-K document?
어떤 국가의 주요 규정이 주식 보상 계획에 영향을 미치는가요?
- What is the total aggregate principal amount of senior notes issued by NVIDIA in June 2021, March 2020, and September 2016, and what were the net proceeds from these offerings after deducting debt discount and issuance costs?
어떤 항목에서 관련 거래 및 이사 독립성에 대한 정보가 제공되며, 이 정보는 어디에서 찾을 수 있습니까?
어떤 조건 하에 참가자의 Option 또는 SAR이 종료되는지에 대한 규정은 무엇입니까?
어떤 조건에서 참가자의 Continuous Service가 끊겼을 때 Option 또는 SAR가 즉시 종료되며 참가자가 해당 Option 또는 SAR를 행사할 수 없게 되는지에 대한 규정은 무엇입니까?
Baseline eval for gpt-3.5-turbo
LLM Evaluation 라이브러리인 RAGAS와 Evaluate Module을 모두 사용하여 기본 모델을 평가해 보겠습니다.
Eval with ragas
다음 두 가지 지표를 사용할 것입니다:
answer_relevancy(답변 관련성) - 생성된 답변이 프롬프트와 얼마나 관련성이 있는지 측정합니다. 생성된 답변이 불완전하거나 중복 정보가 포함되어 있으면 점수가 낮아집니다. 이는 생성된 답변을 사용하여 LLM이 주어진 문제를 생성할 확률을 계산하여 정량화됩니다. 값 범위는 (0,1)이며, 높을수록 좋습니다.
faithfulness(충실도) - 주어진 문맥에 대해 생성된 답변의 사실적 일관성을 측정합니다. 이는 생성된 답변에서 문장을 생성한 다음 각 문장을 문맥과 대조하여 검증하는 다단계 패러다임을 사용하여 수행됩니다. 답변은 (0,1) 범위로 스케일링됩니다. 높을수록 좋습니다.
questions = []
with open("./fine-tune/eval_questions.txt", "r") as f:
for line in f:
questions.append(line.strip())
from llama_index.core import VectorStoreIndex
# limit the context window to 2048 tokens so that refine is used
from llama_index.core import Settings
Settings.context_window = 2048
index = VectorStoreIndex.from_documents(
documents,
)
query_engine = index.as_query_engine(similarity_top_k=2, llm=gpt_35_llm)
contexts = []
answers = []
for question in questions:
response = query_engine.query(question)
contexts.append([x.node.get_content() for x in response.source_nodes])
answers.append(str(response))
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import answer_relevancy, faithfulness
ds = Dataset.from_dict(
{
"question": questions,
"answer": answers,
"contexts": contexts,
}
)
result = evaluate(ds, [answer_relevancy, faithfulness])
print(result)
import pandas as pd
pd.set_option('display.max_colwidth', 200)
result.to_pandas().head()
GPT4 to collect training data
여기서는 GPT-4와 OpenAIFineTuningHandler를 사용하여 학습할 데이터를 수집합니다.
from llama_index.llms.openai import OpenAI
from llama_index.finetuning.callbacks import OpenAIFineTuningHandler
from llama_index.core.callbacks import CallbackManager
finetuning_handler = OpenAIFineTuningHandler()
callback_manager = CallbackManager([finetuning_handler])
llm = OpenAI(model="gpt-4-turbo", temperature=0.3)
llm.callback_manager = callback_manager
questions = []
with open("./fine-tune/train_questions.txt", "r") as f:
for line in f:
questions.append(line.strip())
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex.from_documents(
documents,
)
query_engine = index.as_query_engine(similarity_top_k=2, llm=llm)
for question in questions:
response = query_engine.query(question)
Create OpenAIFinetuneEngine
FinetuneEngine은 fine-tune 작업을 시작하고 나머지 LlamaIndex 워크플로에 직접 플러그인할 수 있는 LLM 모델을 반환하는 작업을 처리합니다.기본 생성자를 사용하지만 from_finetuning_handler 클래스 메서드를 사용하여 이 엔진에 finetuning_handler를 직접 전달할 수도 있습니다.
Wrote 0 examples to ./fine-tune/finetuning_events.jsonl
from llama_index.finetuning import OpenAIFinetuneEngine
finetune_engine = OpenAIFinetuneEngine(
"gpt-4-turbo",
"./fine-tune/finetuning_events.jsonl",
# start_job_id="<start-job-id>" # if you have an existing job, can specify id here
)
finetune_engine.finetune()
finetune_engine.get_current_job()
OpenAI에서 미세 조정 작업이 성공적으로 완료될 때까지 여기서 몇 분 정도 기다리면 OpenAI에서 미세 조정된 모델을 사용할 준비가 되었음을 알리는 이메일이 발송됩니다.
from llama_index.llm.openai import OpenAI
from llama_index.finetuning.callbacks import OpenAIFineTuningHandler
from llama_index.core.callbacks import CallbackManager
questions = []
with open("eval_questions.txt", "r") as f:
for line in f:
questions.append(line.strip())
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine(similarity_top_k=2, llm=ft_llm)
contexts = []
answers = []
for question in questions:
response = query_engine.query(question)
contexts.append([x.node.get_content() for x in response.source_nodes])
answers.append(str(response))
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import answer_relevancy, faithfulness
ds = Dataset.from_dict(
{
"question": questions,
"answer": answers,
"contexts": contexts,
}
)
result = evaluate(ds, [answer_relevancy, faithfulness])
print(result)
evaluating with [answer_relevancy] {'ragas_score': 0.8680, 'answer_relevancy': 0.9607, 'faithfulness': 0.7917}
import pandas as pd
pd.set_option('display.max_colwidth', 200)
result.to_pandas()
Eval with evaluation module
# eval for hallucination
evaluator = ResponseEvaluator(llm=llm_gpt4)
total_correct, all_results = evaluate_query_engine(evaluator, query_engine, questions)
print(f"Hallucination? Scored {total_correct} out of {len(questions)} questions correctly.")
# eval for answer quality
evaluator = QueryResponseEvaluator(llm=llm_gpt4)
total_correct, all_results = evaluate_query_engine(evaluator, query_engine, questions)
print(f"Response satisfies the query? Scored {total_correct} out of {len(questions)} questions correctly.")
Exploring difference
index = VectorStoreIndex.from_documents(documents)
questions = []
with open("eval_questions.txt", "r") as f:
for line in f:
questions.append(line.strip())
from llama_index.finetuning import generate_qa_embedding_pairs
from llama_index.core.evaluation import EmbeddingQAFinetuneDataset
from llama_index.llms.openai import OpenAI
이제 LLM(gpt-3.5-turbo)을 사용하여 말뭉치의 각 텍스트 청크를 문맥으로 사용하여 질문을 생성합니다.각 쌍(생성된 질문, 문맥으로 사용된 텍스트 청크)은 (훈련 또는 평가용) 미세 조정 데이터 세트의 데이터 포인트가 됩니다.
합성(LLM 생성) 데이터 세트에 대한 미세 조정이 오픈소스 임베딩 모델을 크게 개선한다는 것을 보여줍니다.
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import VectorStoreIndex
from llama_index.core.schema import TextNode
from tqdm.notebook import tqdm
import pandas as pd
def evaluate(
dataset,
embed_model,
top_k=5,
verbose=False,
):
corpus = dataset.corpus
queries = dataset.queries
relevant_docs = dataset.relevant_docs
nodes = [TextNode(id_=id_, text=text) for id_, text in corpus.items()]
index = VectorStoreIndex(nodes, embed_model=embed_model, show_progress=True)
retriever = index.as_retriever(similarity_top_k=top_k)
eval_results = []
for query_id, query in tqdm(queries.items()):
retrieved_nodes = retriever.retrieve(query)
retrieved_ids = [node.node.node_id for node in retrieved_nodes]
expected_id = relevant_docs[query_id][0]
is_hit = expected_id in retrieved_ids # assume 1 relevant doc
eval_result = {
"is_hit": is_hit,
"retrieved": retrieved_ids,
"expected": expected_id,
"query": query_id,
}
eval_results.append(eval_result)
return eval_results
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sentence_transformers import SentenceTransformer
from pathlib import Path
def evaluate_st(
dataset,
model_id,
name,
):
corpus = dataset.corpus
queries = dataset.queries
relevant_docs = dataset.relevant_docs
evaluator = InformationRetrievalEvaluator(queries, corpus, relevant_docs, name=name)
model = SentenceTransformer(model_id)
output_path = "results/"
Path(output_path).mkdir(exist_ok=True, parents=True)
return evaluator(model, output_path=output_path)
Run Evals
OpenAI
ada = OpenAIEmbedding()
ada_val_results = evaluate(val_dataset, ada)