지연된 청킹은 전체 문서 컨텍스트를 유지하면서 더 작고 쉬운 청크로 나누는 솔루션을 제공합니다.
이 기사는 전통적인 순진한 청킹 방법에 대한 더 나은 대안으로 지연된 청킹을 소개하고 점차 구현 방법을 보여줄 것입니다.
Langchain의 헝겊 를 사용하는
Delayed chunking: Preserve context in document segmentation
<:> 컨텍스트 유지 : 지연된 청크는 전체 문서를 먼저 포함시켜 각 블록을 전체 컨텍스트를 유지하도록합니다. 이런 식으로, 텍스트의 참고 문헌과 연결은 블록 임베딩에서 그대로 유지됩니다.
2 단계 : 텍스트를 토큰 화하고 태그 수준 문서를 포함시켜 를 생성합니다.
먼저, Jina의 Embedings-V2-Base-en과 같은 긴 컨텍스트 모델과 호환되는 Tagger를 사용하여 전체 문서를 태그로 나눕니다. 다음으로 긴 컨텍스트 변환기 모델을 사용하여 각 태그에 대한 임베딩을 만듭니다. 이것은 문서의 모든 단어 나 마커가 그 의미를 포착하기 위해 고유 한 임베딩을 얻음을 의미합니다.
Delayed chunking solves this problem by changing the time to split the document. 지연된 청크는 먼저 문서를 청크로 나누는 것이 아니라 긴 컨텍스트 모델을 사용하여 전체 문서를 포함시키는 것입니다. 이 후에야 문서를 작은 덩어리로 나눕니다.
<code>input_text = """Berlin is the capital and largest city of Germany, both by area and by population.
Its more than 3.85 million inhabitants make it the European Union's most populous city, as measured by population within city limits.
The city is also one of the states of Germany, and is the third smallest state in the country in terms of area."""</code>
<code>import json
import requests
def custom_tokenize_jina_api(input_text: str):
url = '<https:></https:>'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ENTER_YOUR_JINA_API_KEY'
}
data = {
"content": input_text,
"tokenizer": "o200k_base",
"return_tokens": "true",
"return_chunks": "true",
"max_chunk_length": "1000"
}
# Make the API request
response = requests.post(url, headers=headers, json=data)
response_data = response.json()
chunks = response_data.get("chunks", [])
i = 1
j = 1
span_annotations = []
for x in response_data['tokens']:
if j == 1:
j = len(x)
else:
j = len(x) + i
span_annotations.append((i, j))
i = j
return chunks, span_annotations
chunks, span_annotations = custom_tokenize_jina_api(input_text)
print(chunks)
print(span_annotations)</code>
<code>['Berlin is the capital and largest city of Germany, both by area and by population.\n\n', "Its more than 3.85 million inhabitants make it the European Union's most populous city, as measured by population within city limits.\n\n", 'The city is also one of the states of Germany, and is the third smallest state in the country in terms of area.']
[(1, 17), (17, 44), (44, 69)]</code>
<code>from transformers import AutoModel
from transformers import AutoTokenizer
# load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('jinaai/jina-embeddings-v2-base-en', trust_remote_code=True)
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-en', trust_remote_code=True)
inputs = tokenizer(input_text, return_tensors='pt')
model_output = model(**inputs)
model_output[0].shape</code>
<code>torch.Size([1, 71, 768]) # 71 代表整个文档中的标记数</code>
두 번째 및 세 번째 블록에서 볼 수 있듯이 전통적인 청킹은 "베를린"이라는 단어와 비교하여 유사성 점수가 70-75%를 보여줍니다. 그러나 지연된 청킹 (전체 문서의 컨텍스트 유지)을 사용 하여이 점수는 82-84%로 증가했습니다. 이는 지연된 청크가 컨텍스트를 보존하고보다 의미있는 임베딩을 만드는 데 더 나은 작업을 수행하여보다 정확한 검색 결과를 초래한다는 것을 시사합니다. <code>def late_chunking(
model_output: 'BatchEncoding', span_annotation: list, max_length=None
):
token_embeddings = model_output[0]
outputs = []
for embeddings, annotations in zip(token_embeddings, span_annotation):
if (
max_length is not None
): # remove annotations which go bejond the max-length of the model
annotations = [
(start, min(end, max_length - 1))
for (start, end) in annotations
if start = 1
]
pooled_embeddings = [
embedding.detach().cpu().numpy() for embedding in pooled_embeddings
]
outputs.append(pooled_embeddings)
return outputs</code>
<code>embeddings = late_chunking(model_output, [span_annotations])[0]
len(embeddings)</code>
<code>3 # 与步骤 1 中的块数匹配</code>
위 내용은 래그에 대한 늦은 청크 : Jina AI와의 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!