<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ian Fukushima on Medium]]></title>
        <description><![CDATA[Stories by Ian Fukushima on Medium]]></description>
        <link>https://medium.com/@ianfukushima?source=rss-4bc10c2ec73b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d9Bqa-KSafD9yNddJ_hOfg.jpeg</url>
            <title>Stories by Ian Fukushima on Medium</title>
            <link>https://medium.com/@ianfukushima?source=rss-4bc10c2ec73b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:29:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ianfukushima/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Harnessing Transformers to Chunk Documents: Exploring an Open Source Model for Context-Aware…]]></title>
            <link>https://medium.com/blue-orange-digital/harnessing-transformers-to-chunk-documents-exploring-an-open-source-model-for-context-aware-e5775c017cd4?source=rss-4bc10c2ec73b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5775c017cd4</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text-chunking]]></category>
            <category><![CDATA[chunking]]></category>
            <dc:creator><![CDATA[Ian Fukushima]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 23:19:15 GMT</pubDate>
            <atom:updated>2024-02-28T23:19:15.855Z</atom:updated>
            <content:encoded><![CDATA[<h3>Harnessing Transformers to Chunk Documents</h3><h4>Exploring an Open Source Model for Context-Aware Document Chunking</h4><p>The performance of Retrieval Augmented Generation (RAG) applications greatly depends on the system’s ability to provide good context for Large Language Models (LLMs) to answer queries. Document chunking is a crucial part of these applications, since documents are usually too large to be entirely added to LLMs context, and doing so is also inefficient. We often want to provide diverse pieces of information for a nuanced and complete answer. This is the motivation behind splitting documents into well-sized and quality chunks which provide us the ability to search for a variety of self-contained chunks to provide context to the LLM.</p><p>This article is a practical guide on how to use a pre-trained transformer model hosted on Hugging Face to chunk a document.</p><h3>Transformer Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*b0F6RJ0Rv-YuIGRJ" /></figure><p>Before jumping into the practical code, let’s quickly discuss the transformer model that we will be using. It is based on the work of <a href="https://arxiv.org/abs/2004.14535">Michal Lukasik, Boris Dadachev, Gonçalo Simões and Kishore Papineni in their paper called “Text Segmentation by Cross Segment Attention”.</a> They propose and compare 3 neural network architectures designed for text segmentation (document chunking) and benchmark them on several datasets.</p><p>Our article will use a transformer model based on their “Cross-Segment BERT” architecture, but implemented as a fine-tuning of the <a href="https://huggingface.co/distilbert/distilbert-base-uncased">DistilBERT model </a>on 40,000 Wikipedia articles. <a href="https://www.linkedin.com/company/blue-orange-digital/mycompany/verification/">Blue Orange Digital</a> trained and published our model on Hugging Face. You can find further descriptions and the model files at <a href="https://huggingface.co/BlueOrangeDigital/distilbert-cross-segment-document-chunking">https://huggingface.co/BlueOrangeDigital/distilbert-cross-segment-document-chunking</a>.</p><h3>Chunking a Document</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTdmVGIhDUt5xIBhj2GrRQ.gif" /></figure><p>For our example, we will chunk an arbitrary Wikipedia article. The whole chunking process is illustrated in the image above. It involves classifying each subsequent sentence pair with our transformer which returns a numeric label for each pair of input sentences. A positive label (1) means that the sentences are not from the same chunk, i.e., the sentences mark a chunk boundary.</p><p>The article text in our example is defined below, and split into sentences.</p><pre>article = &quot;&quot;&quot;<br>Ane Mihailovich is a retired Yugoslavian-American soccer player.<br>He spent at least four seasons in the American Soccer League, four in the North American Soccer League and one in the Major Indoor Soccer League.<br>He also earned five caps with the United States men&#39;s national soccer team in 1977.<br>Mihailovich spent the 1973 and 1974 seasons with the Cleveland Stars in the American Soccer League (ASL).<br>In 1976, Mihailovich signed with the expansion Los Angeles Skyhawks.<br>The Skyhawks went to the ASL title game where the game was tied 1-1 until the Skyhawks’ Steve Ralbovsky was tripped in the penalty area.<br>Mihailovich converted the penalty, beating New York Apollo goalkeeper Gerard Joseph in the lower left hand corner, and the Skyhawks won the game, 2-1.<br>In 1977, Mihailovich jumped the first division Los Angeles Aztecs of the North American Soccer League (NASL).<br>The Aztecs traded him to the Washington Diplomats six games into the 1978 season.<br>The move to the Dips brought a move from forward to defense for Mihailovich.<br>At the end of the 1979 season, the Dips sent Mihailovich to the San Jose Earthquakes in exchange for the Earthquakes first round draft pick in 1982. for the 1980 season, his last in the NASL.<br>While Mihailovich had played as a forward with the Skyhawks, he moved between the midfield and defense in the NASL.<br>He also earned five caps with the U.S. national team in 1977.<br>His first cap was a 3-1 loss to Guatemala on September 18, 1977.<br>His last cap came less than a month later in a 1-0 win over China on October 10, 1977.<br>Ane is now retired and living in Michigan with his wife Patricia.<br>They have 2 children, daughter Nicole and son Sasha.<br>They have 6 grandchildren.<br>Ane is currently coaching Crestwood High School&#39;s Boys Varsity Soccer.<br>He won coach of the year in 2013.<br>&quot;&quot;&quot;<br><br><br>ordered_sentences = article.split(&#39;\n&#39;)[:-1]</pre><p>The transformer model takes as input the concatenation of two sentences, and outputs 0 if the two sentences are from the same section/chunk, and 1 if they are from different ones. So our sentences need a tiny bit of preprocessing:</p><ul><li>Ensure that the sentences do not exceed the token limit of our transformer;</li><li>Concatenate subsequent sentences into pairs, separated by the special [SEP] token.</li></ul><pre>from transformers import DistilBertTokenizer<br><br>model_name = &quot;BlueOrangeDigital/distilbert-cross-segment-document-chunking&quot;<br>tokenizer = DistilBertTokenizer.from_pretrained(model_name)<br><br>def right_truncate_sentence(sentence, tokenizer, max_len):<br>   tokenized = tokenizer.encode(sentence)[1:-1]<br>   if len(tokenized) &gt; max_len:<br>       print(&quot;cut&quot;)<br>   return tokenizer.decode(tokenized[:max_len])<br><br><br>def left_truncate_sentence(sentence, tokenizer, max_len):<br>   tokenized = tokenizer.encode(sentence)[1:-1]<br>   if len(tokenized) &gt; max_len:<br>       print(&quot;cut&quot;)<br>   return tokenizer.decode(tokenized[-max_len:])<br><br>def bucket_pair(left_sentence, right_sentence, tokenizer, max_len):<br>   return left_truncate_sentence(left_sentence, tokenizer, max_len) + &quot; [SEP] &quot; + \<br>       right_truncate_sentence(right_sentence, tokenizer, max_len)<br><br>MAX_LEN = 255<br>pairs = [<br>   bucket_pair(ordered_sentences[i], ordered_sentences[i+1], tokenizer, MAX_LEN)<br>   for i in range(0, len(ordered_sentences) - 1)<br>]</pre><p>The `pairs` list can be passed directly to a Hugging Face text classification pipeline:</p><pre>from transformers import (<br>   AutoModelForSequenceClassification,<br>   TextClassificationPipeline<br>)<br><br>model_name = &quot;BlueOrangeDigital/distilbert-cross-segment-document-chunking&quot;<br><br>id2label = {0: &quot;SAME&quot;, 1: &quot;DIFFERENT&quot;}<br>label2id = {&quot;SAME&quot;: 0, &quot;DIFFERENT&quot;: 1}<br><br>model = AutoModelForSequenceClassification.from_pretrained(<br>   model_name,<br>   num_labels=2,<br>   id2label=id2label,<br>   label2id=label2id<br>)<br><br>pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer)<br><br>predictions = pipe(pairs)</pre><p>As previously mentioned, the `predictions` output will be indicating, for each sentence pair in `pairs`, if they belong to the same chunk or not. To actually arrive at the chunks, we go back to the `ordered_sentences` list and join sentences based on our predictions.</p><pre>n = len(ordered_sentences)<br>chunks_breaks = [<br>  i+1<br>  for i, pred in enumerate(predictions)<br>  if pred[&quot;label&quot;] != &quot;SAME&quot;<br>]<br><br>chunks = [<br>   &quot;\n&quot;.join(ordered_sentences[i:j])<br>   for i, j in zip([0] + chunks_breaks, chunks_breaks + [n])<br>]<br>print(f&quot;Document split into {len(chunks)} chunks.&quot;)<br>print(chunks)</pre><p>Which outputs:</p><pre>Document split into 7 chunks.<br>[<br>  &quot;Ane Mihailovich is a retired Yugoslavian-American soccer player.\nHe spent at least four season in the American Soccer League, four in the North American Soccer League and one in the Major Indoor Soccer League.\nHe also earned five caps with the United States men&#39;s national soccer team in 1977.&quot;,<br>  ...<br>  &quot;Ane is now retired and living in Michigan with his wife Patricia.\nThey have 2 children, daughter Nicole and son Sasha.\nThey have 6 grandchildren.&quot;,<br>  &quot;Ane is currently coaching Crestwood High School&#39;s Boys Varsity Soccer.\nHe won coach of the year in 2013.&quot;<br>]</pre><p>Note that `chunk_breaks` elements are integers that indicate the index of sentences that are the start of a chunk.</p><h3>Closing Thoughts</h3><p>This article has demonstrated a method to chunk documents by using an open source transformer model. It is important to highlight that the model we used was specifically trained on Wikipedia data, and using it on other datasets must be approached with careful consideration.</p><p>If you are interested in other context-aware approaches to document chunking, take a look at our articles linked below, which not only delve into alternative approaches, but also discuss a way to quantitatively evaluate each strategy.</p><ul><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-a-greedy-start-e39a1dff15c3">Document Chunking Guided Journey: A Greedy Start</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503">Document Chunking Guided Journey: Midway Camp with TextTiling</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e">Document Chunking Guided Journey: Final Ascent with Supervised Learning</a></li></ul><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5775c017cd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blue-orange-digital/harnessing-transformers-to-chunk-documents-exploring-an-open-source-model-for-context-aware-e5775c017cd4">Harnessing Transformers to Chunk Documents: Exploring an Open Source Model for Context-Aware…</a> was originally published in <a href="https://medium.com/blue-orange-digital">Blue Orange Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Models: Task-Specific Models vs. LLMs APIs]]></title>
            <link>https://medium.com/blue-orange-digital/language-models-task-specific-models-vs-llms-apis-991c0a8f6347?source=rss-4bc10c2ec73b------2</link>
            <guid isPermaLink="false">https://medium.com/p/991c0a8f6347</guid>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ian Fukushima]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 18:15:21 GMT</pubDate>
            <atom:updated>2024-01-24T19:22:19.501Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparison of Solutions for Language Models Applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kEoDWtV7BH3H6n7K" /></figure><p>Large Language Models (LLMs) have spread the possibilities of AI to everyone. Natural language processing (NLP) tasks that were only achievable by AI engineers with computing resources are now a prompt away for virtually anyone. However, some applications might be better off using smaller, more specialized models. This article discusses three applications of language models, comparing what LLMs have brought to the table versus what fine-tuned task-specific models bring.</p><p>First, let’s define what is meant (in this article) by LLM and by task-specific models.</p><p><strong>LLM Definition: </strong>An NLP model that can be prompt engineered to perform different NLP tasks, notably classification, Q&amp;A, style transfer, and summarization. Furthermore, it is also a capable conversational model, able to code, perform machine translation, etc. These models have at least a billion parameters, typically more.</p><p><strong>Task Specific Model: </strong>A model designed for a specific NLP task, such as machine translation, summarization, or style transfer, with a narrow focus and not extending beyond their designated task. They are optimized to perform their specific task, and do not exhibit the “emergent” capabilities observed in LLMs. Generally speaking, task-specific models are smaller in size and complexity, requiring less compute and data to be trained, and have been seemingly integrated into various applications for a longer time.</p><p>The release of GPT3 API marks a transition point for the applications of NLP in the industry. It allowed virtually anyone to have the capabilities of task specific models (and more) via a simple API call plus some prompt engineering. The interest in improving processes or creating products using these techniques skyrocketed, new releases of LLMs started coming, including great Open Source LLMs as well.</p><p>Now that we have these definitions, let’s jump to the applications. We will cover <strong>(1)</strong> ChatBot applications (with RAG), <strong>(2)</strong> Real-time text classification (Moderation bot), and <strong>(3)</strong> Style transfer (document standardization). For all applications we will discuss LLMs and task specific models as the definitions above, but note that fine-tuning LLMs is also a possibility that is becoming more affordable.</p><h3>ChatBot Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cEJdoaBH5Y9emARJ" /></figure><p>The key aspects to consider for chatbot applications is how broad a conversation can be, and how much external knowledge it will need to provide answers. <strong>LLMs</strong> are exciting due to their ability to maintain open-ended conversations, code, and reason about many things. However, the factual knowledge they provide is oftentimes inaccurate (hallucinations), and it can struggle to answer domain specific questions.</p><p>On the other hand, <strong>smaller models</strong> can be fine-tuned with domain specific vocabulary and knowledge and be used in conversations with a narrow scope. These models can provide more precise and relevant responses within their scope. Of course, this comes with a higher initial investment, but can be more economical in the long run if the application has enough users, as exemplified in the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyMX2rGU2FpTQBtt9EiXbw.png" /><figcaption>Cost evolution as number of requests increases: LLM vs Fine-Tuning.</figcaption></figure><p>However, LLMs can be “buffed” to alleviate its weakness. One approach to reduce the hallucinations, and also to extend LLMs factual knowledge is Retrieval-Augmented Generation (RAG). RAG works by providing external information to the LLM via the prompt, enhancing its ability to answer questions accurately with up-to-date information. Another approach to improve its capacity is prompt engineering, which consists of several techniques, for example the notable <a href="https://arxiv.org/abs/2311.16452">MedPrompt</a> for Q&amp;A.</p><p>Regarding costs, while LLMs generally incur a linear cost increase with usage, reflecting a pay-as-you-go model, fine-tuned models require an upfront investment. However, over time and with increased usage, these fine-tuned models can prove to be more cost-effective, especially for applications with high interaction volumes.</p><p>The table below summarizes the comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXQwAT_NJkNogRrFQkBJ5A.png" /><figcaption>Summary of the comparison between LLMs and Fine-Tuned smaller models for chatbot applications.</figcaption></figure><h3>Text Classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hguXytdc9IxGgmag" /></figure><p>Text classification has a wide range of applications that dates back decades. A classical example is spam detection: it has relied on classification models trained or fine-tuned on large datasets of spam and non-spam samples. The rise of LLMs, however, marked a significant shift in the landscape. The paper <a href="https://arxiv.org/abs/2005.14165">Language Models are Few-Shot Learners</a> demonstrates that LLMs are capable of performing classification with very few examples, a technique referred to as few-shot learning, which lowers the barrier to entry for text classification tasks.</p><p>This section discusses a particular form of text classification: content moderation. Drawing inspiration <a href="https://twitter.com/levelsio/status/1736160681026555956">from a tweet by @levelsio</a>, it is remarkable to see the feasibility of creating a very customizable moderation bot. For $5/month he has an excellent solution that is able to cover 15,000 messages monthly. That is $0.00035 per message. I assume that he uses the API in batches of messages, because if we consider an average of 350 input tokens + 20 output tokens, for 15,000 API calls we would have (as of 2024–01–16) the following costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLWpYJ9PzIpwPVhiwb2InQ.png" /><figcaption>Cost of 15,000 API calls considering 350 input tokens + 20 output tokens in 2024–01–16.</figcaption></figure><p>For comparison, a very simple cloud hosting machine costs around $50 a month. One could host a fine-tuned Bert family model for inference in such a machine. But the fine-tuning itself would need good examples of every behavior we want to ban.</p><p>Now let’s assume that the 15,000 messages are evenly distributed in time. In a 30 day month we have 43200 minutes, which gives us 0.3472 messages per minute. Hosting a machine 24/7 for this sounds wasteful, but would be well justifiable if the number of requests increases — costs would be fixed until a certain load, in contrast with the LLM solution that has costs scaling linearly with number of requests, as exemplified in the previous section graph.</p><p>Another key aspect to consider is adaptability. If we want to add or remove moderation policies, the LLM solution is easily adaptable via the prompt, while the fine-tune solution would require further data labeling and model training. Furthermore, people might update their behavior, be it to bypass the moderation or simply because things change. Again, this means that from time to time a task-specific model needs to be updated, while for an LLM simply updating the prompt can solve the problem.</p><p>The diagram below provides a decision flow to consider when deciding between the options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrAb_-aq-y8b2_wdsN7zOQ.png" /><figcaption>Decision Flow: LLM or task-specific fine-tuned model?</figcaption></figure><h3>Automated Style transfer and Document Standardization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DdA0yyGo1tLBUrdV" /></figure><p>Style transfer is an exciting frontier in document processing. It consists of adapting the style and format of a text to match a predefined one. Models available on platforms like <a href="https://huggingface.co/models?other=style-transfer">Hugging Face 🤗</a>, such as those converting informal to formal text, lay the groundwork for these applications. LLMs, however, enable rapid application of various standards to text. This capability is transformative in fields such as legal document reformulation, engineering documents standardization, corporate branding consistency, technical manual localization, etc.</p><p>In style transfer, the use of specific terminology and the need for domain adaptation are crucial. LLMs can address these needs via few-shot learning, making it an invaluable tool for quickly handling style transfer and document standardization tasks. For task-specific models, a robust dataset of “before and after” examples is vital. With such datasets, it is possible to fine-tune these models to achieve the desired style effectively. Moreover, domain adaptation techniques can further improve the usage of specific terminology and enhance the models’s grasp of the domain.</p><p>Regardless of the solution, style transfer poses two specific technical challenges: maintaining semantic meaning and evaluating the style transfer.</p><p><strong>Maintaining semantic meaning:</strong> Since these applications often involve important documents, maintaining 100% of the intent of the original is crucial. Some specialized models can be used to evaluate the content preservation (e.g. Bi-Enconders and Cross-Encoders). Human review is always necessary in the initial iterations.</p><p><strong>Evaluating Style Transfer:</strong> While test datasets for task-specific models exist abundantly, we do not have the same for LLMs. Regardless, when dealing with novelty documents, evaluating whether the generated text is following the predefined style is essential for confidence in the application. Specialized NLP models can be applied, alongside predetermined tests. Human review is also necessary in initial iterations before handing bulk style transfer jobs over to a model.</p><p>In general, while LLMs have brought great capabilities to this field, using them with precision in volume can be challenging and usually requires human feedback in initial iterations. Because of this, industrial-grade automation applications usually consist of more than one mode to achieve a reliable pipeline with quality metrics.</p><h3>Closing Thoughts</h3><p>As we conclude, several key takeaways emerge from the comparison of Large Language Models (LLMs) and task-specific models:</p><ul><li><strong>Flexibility vs. Precision: </strong>LLMs offer broad flexibility, ideal for a range of tasks, while task-specific models excel in specialized applications.</li><li><strong>Cost and Scalability:</strong> The choice between LLMs and task-specific models often depends on cost-effectiveness and scalability, with LLMs scaling with usage and task-specific models requiring upfront investment, both can offer long-term savings.</li><li><strong>Adaptability:</strong> LLMs adapt quickly to new requirements, whereas task-specific models demand retraining for significant change.</li><li><strong>Ethical Considerations:</strong> Both models come with ethical implications, including data privacy and bias, necessitating careful usage.</li><li><strong>Evolving AI Landscape:</strong> The field of AI in language processing is rapidly advancing, promising more sophisticated close and open source models, new training techniques, new frameworks and infrastructure solutions. Fine-tuning LLMs is also a possibility that has become more affordable, and can take advantage of both worlds.</li></ul><p>In summary, the choice between LLMs and task-specific models is nuanced, depending on specific needs and long-term goals. As AI technology evolves, so too will the strategies for its application, and this will continually shape the future of language processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991c0a8f6347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blue-orange-digital/language-models-task-specific-models-vs-llms-apis-991c0a8f6347">Language Models: Task-Specific Models vs. LLMs APIs</a> was originally published in <a href="https://medium.com/blue-orange-digital">Blue Orange Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Chunking Guided Journey: Final Ascent with Supervised Learning]]></title>
            <link>https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e?source=rss-4bc10c2ec73b------2</link>
            <guid isPermaLink="false">https://medium.com/p/92534033595e</guid>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[text-chunking]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[document-search]]></category>
            <dc:creator><![CDATA[Ian Fukushima]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 20:31:39 GMT</pubDate>
            <atom:updated>2023-11-03T13:02:39.232Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Strategies for Document Segmentation with Python</h4><p>Having ventured through greedy and TextTiling algorithms, we now prepare for the final ascent to an approach that leverage transformers for text embedding, combined with similarity scores and supervised learning.</p><p>We continue to utilize the Wiki 50 dataset by <a href="https://arxiv.org/abs/1803.09337">Omri Koshorek et al.</a> and <a href="https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AADzAd9SDTrBnvs1qLCJY5cza?dl=0">available here</a>, and you can refer to the first article if you need details of how to preprocess the data.</p><p><strong>Note:</strong> This is the final article of a 3 part series. You can check out the algorithms previously presented in the stories below:</p><ul><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-a-greedy-start-e39a1dff15c3">Document Chunking Guided Journey: A Greedy Start</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503">Document Chunking Guided Journey: Midway Camp with TextTiling</a></li></ul><h3>Chunking Algorithm: Embedding Similarity Score + supervised classification</h3><p>In the TextTiling approach, we compare blocks. We can have a more granular comparison by calculating similarity scores at the sentence level, not only between subsequent sentences, but for all sentences that are in a range “k.”</p><p>Diverging from the block comparison methodology inherent in TextTiling, this approach goes beyond the comparison of subsequent blocks. More specifically, it calculates similarity scores that span across all sentences within a specified distance, denoted as “k”, as illustrated in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r_9oPEi-8SnMEFrO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*74wtpJq_Na1ID3ek" /></figure><p>The similarity scores can be used as features for a binary classification problem of identifying if a sentence is the first of a chunk or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6MepVdKEj1I_1WWA" /></figure><p>With the features and labels in hand, we can train any classifier and apply standard ML practices. Below is a simplified approach of the features creation and the model training steps:</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import GridSearchCV<br><br>from sentence_transformers import SentenceTransformer<br><br>def get_features(<br>    document: str,<br>    filename: str,<br>    chunk_sentence_start_positions: List[int],<br>    encoder: tiktoken.core.Encoding,<br>    model: SentenceTransformer,<br>    sentence_end_string: str,<br>    K: int,<br>    train: bool = True,<br>):<br>    &quot;&quot;&quot;<br>   Parameters:<br>    - document: The text to be divided into chunks based on sentence       <br>      boundaries.<br>    - filename: Identifier for the document, which works as a unique ID.<br>    - chunk_sentence_start_positions: Positions of the sentences that initiate <br>      a new chunk. For example, if the positions are [0, 4], then the first and <br>      fifth sentences start a new chunk.<br>    - encoder: Tokenizer used to convert text into<br>      tokens.<br>    - model: Model used to generate embeddings for sentences.<br>    - sentence_end_string (str): A special string that indicates the end of a <br>      sentence.<br>    - K (int): Number of adjacent sentences to the left and right of a given <br>      sentence to calculate similarity with.<br>    - train (bool, optional): Flag to indicate whether the function is being <br>      used for training (True) or testing/prediction (False). Defaults to True.<br><br>    Returns:<br>    - List[List[Union[bool, float, int, str]]]: A list of features for each <br>      sentence in the document. Each entry in the list contains:<br>      - A boolean indicating if the sentence starts a new chunk.<br>      - K similarity scores with K subsequent and preceding sentences.<br>      - The number of sentences in the current chunk (if in train mode).<br>      - The start position of the sentence in the document.<br>      - The filename (ID) of the document.<br><br>    &quot;&quot;&quot;<br>    # List all possible startpoints (position of token subsequent to a <br>    # &quot;sentence_end_string&quot;)<br>    sentence_end_token = encoder.encode(<br>        sentence_end_string, allowed_special={sentence_end_string})<br>    assert len(sentence_end_token) == 1<br><br>    # Sentences<br>    sentences = [<br>        s + sentence_end_string <br>        for s in document.split(sentence_end_string)<br>        if s != &quot;&quot;<br>    ]<br>    sentence_token_len = [<br>        len(encoder.encode(s, allowed_special=&quot;all&quot;))<br>        for s in sentences<br>    ]<br>    sentence_start_positions = [0] +np.cumsum(sentence_token_len)[:-1].tolist()<br>    n_sentences = len(sentences)<br><br>    # Get labeled dataset<br>    embeddings = model.encode(sentences)<br><br>    # Initialize an empty list to store the similarity scores<br>    results = []<br><br>    # We will also create a feature for the number of sentences in the <br>    # current chunk. It is initialized as K, since we will start looking<br>    # at the (K+1)th sentence <br>    chunk_sentences = K<br>    for i in range(K, n_sentences - K):<br>        # Calculate the similarity scores with K subsequent and preceding         <br>        # sentences<br>        similarity_matrix = cosine_similarity(<br>            [embeddings[i]], embeddings[i - K:i + K + 1]<br>        )[0]<br><br>        # If train mode, count the sentence, if test/predict, we need to<br>        # calculate this feature iterative outside the feature creation <br>        if train:<br>            chunk_sentences += 1<br>        else:<br>            chunk_sentences = None<br><br>        results.append(<br>            [i in chunk_sentence_start_positions] + \<br>            list(similarity_matrix) + \<br>            [chunk_sentences, sentence_start_positions[i], filename]<br>        )<br><br>        # If the sentence is the first of a chunk, restart the chunk <br>  # number of sentences count<br>        if i in chunk_sentence_start_positions:<br>            chunk_sentences = -1<br><br>    return results<br><br><br>K = 3<br><br>model_name=&quot;sentence-transformers/all-mpnet-base-v2&quot;<br>model = SentenceTransformer(model_name)<br><br>similarity_features = train_df.apply(<br>        lambda x: get_features(<br>            x.text, x.filename, x.chunk_start_sentence_position,<br>            enc,<br>      model,<br>            &quot;&lt;|end_sentence|&gt;&quot;,<br>            K,<br>            True<br>        )<br>        , axis=1<br>)<br><br>list_of_similarity_features = [<br>    chunk_features<br>    for article_features_list in similarity_features<br>    for chunk_features in article_features_list<br>]<br><br>sl_train_df = pd.DataFrame(<br>    list_of_similarity_features,<br>    columns=[&quot;y&quot;] + [f&quot;sim_lag_{k}&quot; for k in range(K, 0, -1)] + \<br>        [f&quot;sim_lead_{k}&quot; for k in range(K+1)] + \<br>        [&quot;chunk_sentences&quot;, &quot;sentence_start_positions&quot;, &quot;filename&quot;]<br>)<br><br><br># Train the classifier<br>features = [f&quot;sim_lag_{k}&quot; for k in range(K, 0, -1)] + \<br>    [f&quot;sim_lead_{k}&quot; for k in range(2, K+1)] + \<br>    [&quot;chunk_sentences&quot;]<br><br>features = [&quot;chunk_sentences&quot;]<br>parameters = {<br>    &quot;n_estimators&quot;: [3, 4, 5, 10],<br>    &quot;max_depth&quot;: [2, 3, 4],<br>    &quot;class_weight&quot;: [&#39;balanced_subsample&#39;, &#39;balanced&#39;],<br>}<br><br>rfc = RandomForestClassifier()<br>clf = GridSearchCV(rfc, parameters, cv=5, return_train_score=True)<br><br>clf.fit(X=sl_train_df[features], y=sl_train_df[&quot;y&quot;])<br><br>clf.best_estimator_</pre><p>Note that predictions necessitate an iterative approach, given that the construction of chunk_sentences depends on preceding predictions. Also, we can add more features to the classifier, such as leads and lags of the similarity scores. Below is an example output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*sOoI5jKklELi3inw" /></figure><h3>Comparative Analysis: Quantitative Evaluation of the Approaches</h3><p>The statistics of the error, defined as the cumulative difference between the actual and predicted positions of the starting token of a chunk, are presented below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*pfIwZa26rgMBpD6P" /></figure><p>Error statistics for different document chunking algorithms</p><p>Refer to the first article for a detailed definition of the error calculation.</p><h3>A Note of Caution</h3><p>The aforementioned results provide a baseline understanding of one way to quantify the quality of chunks. It’s imperative to recognize the specificity and constraints of our train and test sets. Furthermore, the simplification in the supervised learning approach warrants consideration. Thus, I encourage you to perceive the results as an illustrative exercise, and not a table to choose an algorithm from.</p><p>It is prudent to engage in experimentation with these approaches on your data, ensuring the selected strategy works in your application.</p><h3>Other approaches</h3><ul><li><a href="https://arxiv.org/pdf/2207.00939.pdf">Summarization</a> can condense information for later information retrieval or search;</li><li><a href="https://arxiv.org/pdf/2004.14535.pdf">Cross Segment Attention Transformer</a>: fine tune HuggingFace cross encoder transformers to segment text;</li><li><a href="https://huggingface.co/blog/bertopic">BERTopic</a> can classify each sentence of your document in a topic;</li><li><a href="https://github.com/koomri/text-segmentation">Text Segmentation as a Supervised Learning Task</a> formulates the problem as a supervised learning problem, and provide trainable neural nets to segment text;</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92534033595e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e">Document Chunking Guided Journey: Final Ascent with Supervised Learning</a> was originally published in <a href="https://medium.com/blue-orange-digital">Blue Orange Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Chunking Guided Journey: Midway Camp with TextTiling]]></title>
            <link>https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503?source=rss-4bc10c2ec73b------2</link>
            <guid isPermaLink="false">https://medium.com/p/162800e08503</guid>
            <category><![CDATA[text-chunking]]></category>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[document-search]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ian Fukushima]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 21:06:25 GMT</pubDate>
            <atom:updated>2023-11-03T13:05:02.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Strategies for Document Segmentation with Python</h4><p>Having started our journey with the simplistic greedy algorithm, we now elevate our approach by delving into an approach designed to consider the semantic meaning of the text by tokenizing it: The TextTiling algorithm.</p><p>For consistency and comparison, we continue using the Wiki 50 dataset, originally presented by <a href="https://arxiv.org/abs/1803.09337">Omri Koshorek et al.</a> and <a href="https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AADzAd9SDTrBnvs1qLCJY5cza?dl=0">available here</a>. Please refer to the first article of the series for detailed Python preprocessing code.</p><p><strong>Note: </strong>This is the second article of a three part series. You can check out the other articles in the stories below:</p><ul><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-a-greedy-start-e39a1dff15c3">Document Chunking Guided Journey: A Greedy Start</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e">Document Chunking Guided Journey: Final Ascent with Supervised Learning</a></li></ul><h3>Chunking Algorithm: TextTiling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BeHaULPEmszMHNr9XUrjXw.gif" /></figure><p>TextTiling was introduced in 1997 by MA Hearst. You can check out her seminal paper <a href="https://aclanthology.org/J97-1003.pdf">here</a>. The algorithm is capable of dividing documents into chunks, each containing a specific topic, by comparing pseudo-sentences semantic meaning using a tokenizer (or embedding methods) along with a similarity measure.</p><p><strong>Objective</strong>: To segment a document into topically coherent multi-paragraph chunks.</p><h4>Algorithm Steps:</h4><p><strong>1. Tokenization and Block Formation</strong></p><p>Tokenize the text into words and divide it into pseudo-sentences.</p><p><strong>2. Lexical Score Calculation</strong></p><p>Compute a score (cosine similarity) that represents the degree of lexical similarity between adjacent blocks, considering a sliding window of blocks.</p><p><strong>3. Boundary Identification</strong></p><p>Identify boundaries between topically coherent sections by locating the local minima (valleys) in the lexical score graph.</p><h4>Python (nltk) implementation</h4><p>The python “nltk” library provides a TextTiling implementation. The main hyperparameters to look at are “w” and “k.” They represent the size of the pseudo-sentences, and the size of the blocks used in the Lexical Score calculation score, respectively. We can tune them using our training dataset.</p><pre>from nltk.tokenize.texttiling import TextTilingTokenizer<br><br>def preprocess_tiling_output(tt_text):<br>    tt_text = tt_text.replace(&quot;\n\n&quot;, &quot;&lt;|end_sentence|&gt;&quot;) + \<br>        &quot;&lt;|end_sentence|&gt;&quot;<br>    if tt_text.startswith(&quot;&lt;|end_sentence|&gt;&quot;):<br>        return tt_text[len(&quot;&lt;|end_sentence|&gt;&quot;):]<br>    return tt_text<br><br>def preprocess_tiling_input(text):<br>    return text.replace(&quot;&lt;|end_sentence|&gt;&quot;, &quot;\n\n&quot;)<br><br>def tiling_predict_chunk_startpoints(<br>    document: str,<br>    encoder: tiktoken.core.Encoding,<br>    w=40,<br>    k=20,<br>) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Returns a list of chunk start points (position of the first token of <br>    each chunk) by using the &quot;nltk.tokenize.texttiling.TextTilingTokenizer.&quot;<br><br>    The parameters &quot;w&quot; and &quot;k&quot; specific for the tokenizer, and can be tuned.<br><br>    &quot;&quot;&quot;<br>    tiling_tokenizer = TextTilingTokenizer(w=w, k=k)<br>    sections = tiling_tokenizer.tokenize(<br>        preprocess_tiling_input(document)<br>    )<br><br>    startpoint = 0<br>    preds = [startpoint]<br><br>    for section in sections:<br>        pp_section = preprocess_tiling_output(section)<br>        startpoint += len(encoder.encode(pp_section, allowed_special=&quot;all&quot;))<br>        preds.append(startpoint)<br><br>    return preds</pre><h4>Alternative implementation: transformer embeddings</h4><p>The “nltk” implementation leverages a tokenizer to perform step 1. Alternatively, we can use a transformer model to embed the text, which might be more sensitive in capturing semantic changes throughout the document. Here is a python implementation that utilizes HuggingFace SentenceTransformer library, along with nltk. Note that in this implementation we do not define “w” and “k.” It simplifies comparing groups of subsequent sentences.</p><pre>def embd_cossim_predict_chunk_startpoints(<br>    document: str,<br>    encoder: tiktoken.core.Encoding,<br>    sentence_end_string: int,<br>    model: SentenceTransformer,<br>) -&gt; List[int]:<br>    # List all possible startpoints (position of token subsequent to a<br>    # &quot;sentence_end_string&quot;)<br>    sentence_end_token = encoder.encode(<br>        sentence_end_string, allowed_special={sentence_end_string}<br>    )<br>    assert len(sentence_end_token) == 1<br><br>    document_tks = encoder.encode(<br>        document, allowed_special={sentence_end_string}<br>    )<br><br>    possible_startpoints = [<br>        i + 1 for i, token in enumerate(document_tks)<br>        if token == sentence_end_token[0]<br>    ]<br><br>    # Split the document into sentences<br>    sentences = [<br>        sentence for sentence in document.split(sentence_end_string)<br>        if sentence != &quot;&quot;<br>    ]<br>    sentences_joined = []<br>    for i in range(len(sentences) // 2):<br>        sentences_joined.append(<br>            sentences[i * 2] + sentences[i * 2 + 1]<br>        )<br>    if len(sentences) % 2 == 1:<br>        sentences_joined.append(sentences[-1])<br>    <br>    possible_startpoints = [<br>        sp for i, sp in enumerate(possible_startpoints) if i % 2 == 0<br>    ]<br><br>    # Measure similarity between subsequent sentences<br>    similarity_scores = sentences_cossim(<br>        list(zip(sentences_joined[:-1], sentences_joined[1:]))<br>        , model<br>    ).tolist()<br><br>    # Return points with similarit that are &quot;too low&quot;<br>    tiling_tokenizer = TextTilingTokenizer()<br>    s = smooth(<br>        np.array(similarity_scores),<br>        window_len=min(len(sentences_joined) // 9, 11)<br>    )<br><br>    segment_boundaries = tiling_tokenizer._identify_boundaries(<br>        tiling_tokenizer._depth_scores(s)<br>    )<br><br>    return [0] + [<br>        sp for sp, bdr in zip(possible_startpoints, segment_boundaries)<br>        if bdr &gt; 0<br>    ]</pre><h4>Chunking visualization</h4><p>The TextTiling approach has a straightforward visualization: plotting the similarity between two successive pseudo-sentence blocks. The valleys — clearly discernible on the graph — are classified by the algorithm as the initiation point of a new chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/0*yVZVZDTHPkkh8Z6s" /></figure><p>Here is an example output. The color changes represent the source text’s actual sections, while each paragraph is a predicted chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*rQnteSSFQh7XMyNx" /></figure><p>Example output: color changes represent the source text’s actual sections, while each paragraph is a chunk generated by the TextTiling algorithm</p><h3>Quantitative Evaluation</h3><p>The statistics of the error, defined as the cumulative difference between the actual and predicted positions of the starting token of a chunk, are presented below for the greedy and the two TextTiling approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*0ZdHpOnSCB_Wd3vR" /></figure><p>Statistics for the error produced by the greedy algorithm and the TextTiling algorithms</p><p>Refer to the first article for a detailed definition of the error calculation.</p><h3>A Note of Caution</h3><p>The aforementioned results provide a baseline understanding of one way to quantify the quality of chunks. It’s imperative to recognize the specificity and constraints of our train and test sets — it is limited in size — and to have a specific definition of what a chunk is. I encourage you to try the approaches on your own data, selecting the strategy that best fits your needs.</p><h3>Coming Up Next</h3><p>In the next days we will be releasing yet another approach to chunk documents. Stay tuned by following us on <a href="https://medium.com/@BlueOrangeDigital">Medium</a> and <a href="https://www.linkedin.com/company/blue-orange-digital/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162800e08503" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503">Document Chunking Guided Journey: Midway Camp with TextTiling</a> was originally published in <a href="https://medium.com/blue-orange-digital">Blue Orange Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Chunking Guided Journey: A Greedy Start]]></title>
            <link>https://medium.com/blue-orange-digital/document-chunking-guided-journey-a-greedy-start-e39a1dff15c3?source=rss-4bc10c2ec73b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e39a1dff15c3</guid>
            <category><![CDATA[document-search]]></category>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <dc:creator><![CDATA[Ian Fukushima]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 18:17:16 GMT</pubDate>
            <atom:updated>2023-11-03T13:10:13.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uu6AbDAT4NWIPXPh5H37Ag.png" /></figure><h3>Exploring Strategies for Document Segmentation with Python</h3><p>With the popularization of LLMs APIs, the interest in document search has risen. Frameworks that orchestrate LLMs provide connections and interfaces that interact with vector databases, yet there is still a gap when it comes to algorithms designed to effectively chunk extensive documents.</p><p>Such algorithms are important since they improve downstream tasks like summarization and document search, and they are also necessary for optimizing “chat with your data” applications. These applications require the retrieval of specific document excerpts that are concise enough to fit into prompts and sufficiently informative to answer user queries.</p><p>The term chunking is being widely used nowadays, but in the scientific literature terms like “<strong>text/document segmentation</strong>” and “<strong>topic modeling</strong>” have more frequent utilization. We will embark into three pragmatic approaches — each elucidated with Python code:</p><ul><li><strong>(This article) Greedy Approach</strong>: Approximate Chunks Length to a Predefined Value</li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503"><strong>TextTiling:</strong> The nltk Implementation and a Custom Implementation Leveraging Embeddings</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e"><strong>Embeddings + Similarity Scores + Supervised Classification</strong></a></li></ul><p>Employing a labeled dataset, we will also explore a method to evaluate the efficacy of chunking strategies.</p><h3><strong>Wiki 50 and Wiki 727K datasets</strong></h3><p>We will use a labeled dataset, commonly used in text segmentation scientific literature, called Wiki 50. It is a test version of the larger Wiki 727K dataset. It consists of 50 and 727,000 Wikipedia articles, respectively, and each article section is considered a chunk. The dataset is described and provided by<a href="https://arxiv.org/abs/1803.09337"> Omri Koshorek et al.</a> and is<a href="https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AADzAd9SDTrBnvs1qLCJY5cza?dl=0"> available here</a>.</p><p>The code below processes our documents.</p><pre>import re<br><br>cl100k_base = tiktoken.get_encoding(&quot;cl100k_base&quot;)<br><br>enc = tiktoken.Encoding(<br>    name=&quot;cl100k_im&quot;,<br>    pat_str=cl100k_base._pat_str,<br>    mergeable_ranks=cl100k_base._mergeable_ranks,<br>    special_tokens={<br>        **cl100k_base._special_tokens,<br>        &quot;&lt;|new_section|&gt;&quot;: 100264,<br>        &quot;&lt;|end_sentence|&gt;&quot;: 100265,<br>    },<br>)<br><br>def load_and_preprocess(wiki_doc_filename):<br><br>    with open(wiki_doc_filename, &quot;r&quot;) as f:<br>        wiki_doc = f.read()<br><br>    # Replace the delimitation sections with &quot;&lt;|new_section|&gt;&quot; special token<br>    wiki_doc_sep = re.sub(r&#39;========,\d+,[^\n]+\n&#39;, &#39;&lt;|new_section|&gt;&#39;, wiki_doc)<br><br>    # Remove empty sections<br>    wiki_doc_sep = re.sub(<br>        r&#39;(\&lt;\|new_section\|\&gt;)+&#39;,<br>        &#39;&lt;|new_section|&gt;&#39;,<br>        wiki_doc_sep<br>    )<br><br>    # Count sections<br>    n_sections = wiki_doc_sep.count(&quot;&lt;|new_section|&gt;&quot;)<br><br>    # Utilize special new sentence token<br>    wiki_doc_sep = wiki_doc_sep.replace(&quot;\n&quot;, &quot;&lt;|end_sentence|&gt;&quot;)<br><br>    # Position of the first token of new chunks (excluding special new section <br>    # token)<br>    doc_enc = enc.encode(wiki_doc_sep, allowed_special=&quot;all&quot;)<br>    chunk_start_positions = []<br>    for i, token in enumerate(doc_enc):<br>        if token == 100264:<br>            chunk_start_positions.append(i - len(chunk_start_positions))<br>            <br>    doc_len = len(doc_enc) - len(chunk_start_positions)<br><br>    # Position of the sentence that starts a new section<br>    sentences = [s for s in wiki_doc_sep.split(&quot;&lt;|end_sentence|&gt;&quot;) if s != &quot;&quot;]<br>    chunk_start_sentence_position = [<br>        i for i, s in enumerate(sentences) <br>        if s.startswith(&quot;&lt;|new_section|&gt;&quot;)<br>    ]<br><br>    return (<br>        wiki_doc_filename,<br>        wiki_doc_sep.replace(&quot;&lt;|new_section|&gt;&quot;, &quot;&quot;),<br>        wiki_doc,<br>        chunk_start_positions,<br>        chunk_start_sentence_position,<br>        doc_len,<br>        n_sections,<br>    )</pre><p>We store the data into train and test pandas DataFrames, with the following columns:</p><ul><li><strong>original</strong>: the original article text;</li><li><strong>text</strong>: the article text without the section headers — this is what we expect to see in practice when chunking;</li><li><strong>chunk_start_position (THIS IS OUR TARGET)</strong>: a list with the positions of the first token of each chunk;</li><li><strong>chunk_start_sentences_position</strong>: a list with the position of the first sentence that start each chunk;</li><li><strong>doc_len</strong>: number of tokens in the article;</li><li><strong>n_sections</strong>: number of sections/chunks in the article.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*CQi4J1ea3GDhgzke" /><figcaption>The dataset used to train and test our chunking algorithms</figcaption></figure><h3>Chunking Algorithm: Greedy Approximation of Token Length</h3><p>As a baseline, the greedy approximation of token length, which is semantically agnostic, offers a quick and straightforward strategy for initial prototyping or applications where rapid deployment takes precedence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*TDHImZqpRV5UgMMX" /><figcaption>Greedy algorithm illustration</figcaption></figure><p><strong>Objective</strong>: Divide a document into text chunks, where each chunk’s token length approximates a predefined desired length, with new chunks starting immediately after a specified end-token.</p><p><strong>Definitions</strong>:</p><p><em>“desired_len”</em>: The target number of tokens per chunk.</p><p><em>“chunk_end_token”</em>: The token indicating potential starting points for new chunks.</p><h4>Algorithm Steps:</h4><p><strong>1. Tokenize the Document</strong></p><ul><li>Input the raw document text.</li><li>Utilize the specified token encoding method to tokenize the document.</li></ul><p><strong>2. Identify Possible Chunk Start Points</strong></p><ul><li>Scan through the tokenized document.</li><li>Every position following a <em>chunk_end_token</em> is logged as a potential starting point for a new chunk.</li></ul><p><strong>3. Initialize the First Chunk</strong></p><p>The first chunk always starts with the first token of the document.</p><p><strong>4. Greedy Chunk Formation</strong></p><p>For each potential chunk starting point:</p><ul><li>Calculate the ‘error’ for both the current candidate and the next one: the absolute difference between the <em>desired_len</em> and the resulting chunk length.</li><li>If the current candidate provides a chunk size closer to <em>desired_len</em> than the next candidate, finalize the current chunk and prepare to begin a new one from the current candidate point.</li><li>Otherwise, consider the next candidate in the subsequent iteration.</li></ul><p><strong>5. Output the Chunks</strong></p><p>Return the actual starting points of the determined chunks.</p><h4>Python implementation:</h4><pre>def greedy_predict_chunk_startpoints(<br>    document: str,<br>    desired_len: int,<br>    encoder: tiktoken.core.Encoding,<br>    chunk_end_token: int<br>) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Returns a list of chunk start points (position of the first token of each <br>    chunk) based on &quot;desired_len.&quot; The &quot;document&quot; string is encoded using<br>    &quot;encoder.&quot; The possible starting points are infered based on <br>    &quot;chunk_end_token&quot;: the token subsequent to a end token may<br>    be the start of a chunk.<br><br>    The document is split based &quot;desired_len&quot;, which is the desired number of<br>    tokens in each chunk, which won&#39;t be exactly achieved, but approximated.<br><br>    &quot;&quot;&quot;<br>    # List all possible startpoints (position of token subsequent to a <br>    # &quot;chunk_end_token&quot;)<br>    possible_startpoints = [<br>        i + 1<br>        for i, token in enumerate(encoder.encode(<br>            document, allowed_special=&quot;all&quot;))<br>        if token == chunk_end_token<br>    ]<br><br>    # Starting at the beggining of the document (first startpoint is zero)<br>    startpoints_pred = [0]<br><br>    # Chose the startpoints that makes chunk have a length closer to the <br>    # desired<br>    startpoints_zip = zip(possible_startpoints[:-1], possible_startpoints[1:])<br>    for candidate, next_candidate in startpoints_zip:<br><br>        candidate_error = abs((candidate - startpoints_pred[-1]) - desired_len)<br>        next_candidate_error = abs(<br>            (next_candidate - startpoints_pred[-1]) - <br>            desired_len<br>        )<br><br>        # If next candidate is worse, all subsequents one will be too<br>        if candidate_error &lt; next_candidate_error:<br>            startpoints_pred.append(candidate)<br><br>    return startpoints_pred</pre><h4>Chunking visualization</h4><p>Here is an example output. The color changes represent the source text’s actual sections, while each paragraph is a predicted chunk. In this particular case, we can notice that the generated chunks are smaller than the source text’s sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*3G8YUnBxWm7zdNAg" /><figcaption>Example output: color changes represent the original source text’s actual sections, while each paragraph is a chunk generated by the greedy algorithm</figcaption></figure><h3>Quantitative Evaluation</h3><h4>Error Definition</h4><p>The error is defined as the cumulative difference between the actual and predicted positions of the starting token of a chunk. For instance, let’s consider a document with actual token starting positions <em>actual = [0, 50, 100, 200]</em> and predicted positions <em>pred = [0, 49, 105, 180]</em>. The error, in this case, would be computed as <em>|0–0| + |50–49| + |100–105| + |200–180| = 26</em>. Should the arrays of predicted and actual starting positions diverge in length, the last value of the shorter array is repeated to equalize them before calculating the error. An example being: if <em>pred = [0, 49, 150]</em>, the error becomes <em>|0–0| + |50–49| + |100–150| + |200–150| = 101</em>.</p><h4>Evaluation Metric</h4><p>Subsequently, evaluating an algorithm’s overall performance becomes feasible by employing metrics like the Root Mean Squared Error, Mean Absolute Error, etc.</p><p>Here is the error distribution for the greedy approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*Wn4InxWLxIsvSexQ" /><figcaption>Statistics for the error produced by the greedy algorithm</figcaption></figure><p>At the end of our journey through the 3 algorithms, we will quantitatively compare all 3 algorithms’ error rates.</p><h4>A Note of Caution</h4><p>It’s imperative to recognize the specificity and constraints of our train and test sets — they define chunks as literal sections, and are reduced in size to speed up the demonstrations. Thus, I encourage you to perceive the quantitative results as an illustrative exercise, and know that it is prudent to engage in experimentation with the approaches on your data, ensuring the selected strategy works in your application.</p><p>Also, our first algorithm focuses on the length of each chunk, ignoring the semantic intricacies within. It offers a quick solution for prototyping, and the forthcoming algorithms in this series will provide more sophisticated chunking solutions.</p><h3>Coming Up Next</h3><p>In the next stories, we cover TextTile and a Supervised Learning approach:</p><ul><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-midway-camp-with-texttiling-162800e08503">Document Chunking Guided Journey: Midway Camp with TextTiling</a></li><li><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-final-ascent-with-supervised-learning-92534033595e">Document Chunking Guided Journey: Final Ascent with Supervised Learning</a></li></ul><p>Follow us on <a href="https://medium.com/@BlueOrangeDigital">Medium</a> and <a href="https://www.linkedin.com/company/blue-orange-digital/">LinkedIn</a> for more content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e39a1dff15c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blue-orange-digital/document-chunking-guided-journey-a-greedy-start-e39a1dff15c3">Document Chunking Guided Journey: A Greedy Start</a> was originally published in <a href="https://medium.com/blue-orange-digital">Blue Orange Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>