-
Notifications
You must be signed in to change notification settings - Fork 25.2k
Add recursive chunker #126866
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dan-rubinstein
wants to merge
5
commits into
elastic:main
Choose a base branch
from
dan-rubinstein:recursive-chunking-strategy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add recursive chunker #126866
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5167b21
Add recursive chunker
dan-rubinstein 7d9e07c
Update docs/changelog/126866.yaml
dan-rubinstein 8418223
Merge branch 'main' into recursive-chunking-strategy
dan-rubinstein 0685124
Clean up separator sets and add asMap function for RecrusiveChunkingS…
dan-rubinstein f40947a
Add javadoc for chunker, add tests, reduce word counting operations
dan-rubinstein File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
pr: 126866 | ||
summary: Add recursive chunker | ||
area: Machine Learning | ||
type: enhancement | ||
issues: [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
...ugin/inference/src/main/java/org/elasticsearch/xpack/inference/chunking/ChunkerUtils.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0; you may not use this file except in compliance with the Elastic License | ||
* 2.0. | ||
*/ | ||
|
||
package org.elasticsearch.xpack.inference.chunking; | ||
|
||
import com.ibm.icu.text.BreakIterator; | ||
|
||
public class ChunkerUtils { | ||
|
||
// setText() should be applied before using this function. | ||
static int countWords(int start, int end, BreakIterator wordIterator) { | ||
assert start < end; | ||
wordIterator.preceding(start); // start of the current word | ||
|
||
int boundary = wordIterator.current(); | ||
int wordCount = 0; | ||
while (boundary != BreakIterator.DONE && boundary <= end) { | ||
int wordStatus = wordIterator.getRuleStatus(); | ||
if (wordStatus != BreakIterator.WORD_NONE) { | ||
wordCount++; | ||
} | ||
boundary = wordIterator.next(); | ||
} | ||
|
||
return wordCount; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
153 changes: 153 additions & 0 deletions
153
.../inference/src/main/java/org/elasticsearch/xpack/inference/chunking/RecursiveChunker.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0; you may not use this file except in compliance with the Elastic License | ||
* 2.0. | ||
*/ | ||
|
||
package org.elasticsearch.xpack.inference.chunking; | ||
|
||
import com.ibm.icu.text.BreakIterator; | ||
|
||
import org.elasticsearch.common.Strings; | ||
import org.elasticsearch.inference.ChunkingSettings; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.regex.Pattern; | ||
|
||
/** | ||
* Split text into chunks recursively based on a list of separator regex strings. | ||
* The maximum chunk size is measured in words and controlled | ||
* by {@code maxNumberWordsPerChunk}. For each separator the chunker will go through the following process: | ||
* 1. Split the text on each regex match of the separator. | ||
* 2. Merge consecutive chunks when it is possible to do so without exceeding the max chunk size. | ||
* 3. For each chunk after the merge: | ||
* 1. Return it if it is within the maximum chunk size. | ||
* 2. Repeat the process using the next separator in the list if the chunk exceeds the maximum chunk size. | ||
* If there are no more separators left to try, run the {@code SentenceBoundaryChunker} with the provided | ||
* max chunk size and no overlaps. | ||
*/ | ||
public class RecursiveChunker implements Chunker { | ||
private final BreakIterator wordIterator; | ||
|
||
public RecursiveChunker() { | ||
wordIterator = BreakIterator.getWordInstance(); | ||
} | ||
|
||
@Override | ||
public List<ChunkOffset> chunk(String input, ChunkingSettings chunkingSettings) { | ||
if (chunkingSettings instanceof RecursiveChunkingSettings recursiveChunkingSettings) { | ||
return chunk(input, recursiveChunkingSettings.getSeparators(), recursiveChunkingSettings.getMaxChunkSize(), 0, 0); | ||
} else { | ||
throw new IllegalArgumentException( | ||
Strings.format("RecursiveChunker can't use ChunkingSettings with strategy [%s]", chunkingSettings.getChunkingStrategy()) | ||
); | ||
} | ||
} | ||
|
||
private List<ChunkOffset> chunk(String input, List<String> separators, int maxChunkSize, int separatorIndex, int chunkOffset) { | ||
if (input.length() < 2 || isChunkWithinMaxSize(buildChunkOffsetAndCount(input, 0, input.length()), maxChunkSize)) { | ||
return List.of(new ChunkOffset(chunkOffset, chunkOffset + input.length())); | ||
} | ||
|
||
if (separatorIndex > separators.size() - 1) { | ||
return chunkWithBackupChunker(input, maxChunkSize, chunkOffset); | ||
} | ||
|
||
var potentialChunks = mergeChunkOffsetsUpToMaxChunkSize( | ||
splitTextBySeparatorRegex(input, separators.get(separatorIndex)), | ||
maxChunkSize | ||
); | ||
var actualChunks = new ArrayList<ChunkOffset>(); | ||
for (var potentialChunk : potentialChunks) { | ||
if (isChunkWithinMaxSize(potentialChunk, maxChunkSize)) { | ||
actualChunks.add( | ||
new ChunkOffset(chunkOffset + potentialChunk.chunkOffset.start(), chunkOffset + potentialChunk.chunkOffset.end()) | ||
); | ||
} else { | ||
actualChunks.addAll( | ||
chunk( | ||
input.substring(potentialChunk.chunkOffset.start(), potentialChunk.chunkOffset.end()), | ||
separators, | ||
maxChunkSize, | ||
separatorIndex + 1, | ||
chunkOffset + potentialChunk.chunkOffset.start() | ||
) | ||
); | ||
} | ||
} | ||
|
||
return actualChunks; | ||
} | ||
|
||
private boolean isChunkWithinMaxSize(ChunkOffsetAndCount chunkOffsetAndCount, int maxChunkSize) { | ||
return chunkOffsetAndCount.wordCount <= maxChunkSize; | ||
} | ||
|
||
private ChunkOffsetAndCount buildChunkOffsetAndCount(String fullText, int chunkStart, int chunkEnd) { | ||
var chunkOffset = new ChunkOffset(chunkStart, chunkEnd); | ||
|
||
wordIterator.setText(fullText); | ||
return new ChunkOffsetAndCount(chunkOffset, ChunkerUtils.countWords(chunkStart, chunkEnd, wordIterator)); | ||
} | ||
|
||
private List<ChunkOffsetAndCount> splitTextBySeparatorRegex(String input, String separatorRegex) { | ||
var pattern = Pattern.compile(separatorRegex); | ||
var matcher = pattern.matcher(input); | ||
|
||
var chunkOffsets = new ArrayList<ChunkOffsetAndCount>(); | ||
int chunkStart = 0; | ||
while (matcher.find()) { | ||
var chunkEnd = matcher.start(); | ||
if (chunkStart < chunkEnd) { | ||
chunkOffsets.add(buildChunkOffsetAndCount(input, chunkStart, chunkEnd)); | ||
} | ||
chunkStart = matcher.start(); | ||
} | ||
|
||
if (chunkStart < input.length()) { | ||
chunkOffsets.add(buildChunkOffsetAndCount(input, chunkStart, input.length())); | ||
} | ||
|
||
return chunkOffsets; | ||
} | ||
|
||
private List<ChunkOffsetAndCount> mergeChunkOffsetsUpToMaxChunkSize(List<ChunkOffsetAndCount> chunkOffsets, int maxChunkSize) { | ||
if (chunkOffsets.size() < 2) { | ||
return chunkOffsets; | ||
} | ||
|
||
List<ChunkOffsetAndCount> mergedOffsetsAndCounts = new ArrayList<>(); | ||
var mergedChunk = chunkOffsets.getFirst(); | ||
for (int i = 1; i < chunkOffsets.size(); i++) { | ||
var chunkOffsetAndCountToMerge = chunkOffsets.get(i); | ||
var potentialMergedChunk = new ChunkOffsetAndCount( | ||
new ChunkOffset(mergedChunk.chunkOffset.start(), chunkOffsetAndCountToMerge.chunkOffset.end()), | ||
mergedChunk.wordCount + chunkOffsetAndCountToMerge.wordCount | ||
); | ||
if (isChunkWithinMaxSize(potentialMergedChunk, maxChunkSize)) { | ||
mergedChunk = potentialMergedChunk; | ||
} else { | ||
mergedOffsetsAndCounts.add(mergedChunk); | ||
mergedChunk = chunkOffsets.get(i); | ||
} | ||
|
||
if (i == chunkOffsets.size() - 1) { | ||
mergedOffsetsAndCounts.add(mergedChunk); | ||
} | ||
} | ||
return mergedOffsetsAndCounts; | ||
} | ||
|
||
private List<ChunkOffset> chunkWithBackupChunker(String input, int maxChunkSize, int chunkOffset) { | ||
var chunks = new SentenceBoundaryChunker().chunk(input, new SentenceBoundaryChunkingSettings(maxChunkSize, 0)); | ||
var chunksWithOffsets = new ArrayList<ChunkOffset>(); | ||
for (var chunk : chunks) { | ||
chunksWithOffsets.add(new ChunkOffset(chunk.start() + chunkOffset, chunk.end() + chunkOffset)); | ||
} | ||
return chunksWithOffsets; | ||
} | ||
|
||
private record ChunkOffsetAndCount(ChunkOffset chunkOffset, int wordCount) {} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add Java doc explaining how and what the RecursiveChunker does
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, I'll add this in.