<?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 Witold Pawlak on Medium]]></title>
        <description><![CDATA[Stories by Witold Pawlak on Medium]]></description>
        <link>https://medium.com/@wpawlak87?source=rss-e2b3bfa2bcd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XgvaLKaqd97Jm5XCRz1W7A.jpeg</url>
            <title>Stories by Witold Pawlak on Medium</title>
            <link>https://medium.com/@wpawlak87?source=rss-e2b3bfa2bcd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:26:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wpawlak87/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[Fine-tuning Bielik LLM— part II]]></title>
            <link>https://medium.com/@wpawlak87/fine-tuning-bielik-llm-part-ii-ae5c4d02c80a?source=rss-e2b3bfa2bcd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5c4d02c80a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bielik]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Witold Pawlak]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 22:10:51 GMT</pubDate>
            <atom:updated>2025-05-29T21:17:36.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20Fep-9OQzgShatLkEMAIw.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>This is second part of small series related to LLM fine-tuning!</p><p>The goal of following article is to fine-tune one large language model — Bielik 11B from Speakleash (https://huggingface.co/speakleash). In first part (https://medium.com/@zvit3k/fine-tuning-bielik-llm-from-a-scratch-part-i-af4c9916e731) we focused on data preparation. To achieve this, we generated data based on the polish legal document — consumer rights act. Then, we measured the quality of the generated data using various metrics (no-LLM and LLM based). As we proved the good quality of the generated question and answers based on the context, we formatted the data in order to follow a specific schema suitable for question-answering task for LLM.</p><p>Now let’s dive deep into the fine-tuning itself!</p><h3><strong>Prerequisites</strong></h3><p>In order to start working with model and fine-tuning let’s install required libraries (also present in requirements.txt). Short intro to libraries:</p><ul><li>bitandbytes — setups config for quantization options</li><li>transformers — core library for using Large Language Models and beyond (all various tasks related to NLP)</li><li>accelerate — Accelerate is a library that enables the same PyTorch code to be run across any distributed configuration by adding just four lines of code. <a href="https://huggingface.co/docs/accelerate/en/index">https://huggingface.co/docs/accelerate/en/index</a></li><li>peft — our gem! Library which allows to finetune small number of extra model paremeters instead of all, which could be costly.</li><li>wandb — weights and biases — useful for tracking the experiments (https://wandb.ai/site/)</li><li>torch, torchvision, torchaudio — core PyTorch libraries for running neural networks.</li></ul><p>Full list of requirements is available in the repository — <a href="https://github.com/witold87/llm-bielik-ft-legal/blob/main/requirements.txt">https://github.com/witold87/llm-bielik-ft-legal/blob/main/requirements.txt</a></p><h3><strong>3…2…1… and action!</strong></h3><p>Let’s start with some helper functions:</p><ul><li>setting appropriate level of logging, because pytorch likes to spam all the output console.</li><li>login to huggingface with credentials to be able to download some models — not every model is available to download without logging in (account is free, for references please visit <a href="https://huggingface.co/">https://huggingface.co/</a>).</li></ul><pre>logging.set_verbosity_warning()<br>notebook_login()</pre><p>To start with, let’s focus on our model. Here, we want to load and setup appropriate model - Bielik 11B (v2.3-Instruct) in our case. We start with quantization config in order to make our model lighter. Then we get the model from HuggingFace Hub.</p><pre>model_name = &#39;speakleash/Bielik-11B-v2.3-Instruct&#39;<br><br>model_config = {<br>        &#39;load_in_4bit&#39;:True,<br>        &#39;bnb_4bit_use_double_quant&#39;:True,<br>        &#39;bnb_4bit_quant_type&#39;:&quot;nf4&quot;,<br>        &#39;bnb_4bit_compute_dtype&#39;:torch.bfloat16<br>}</pre><pre>bnb_config = BitsAndBytesConfig(**model_config)<br><br>model = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=bnb_config, device_map=&quot;auto&quot;)<br><br>tokenizer = AutoTokenizer.from_pretrained(<br>    model_name,<br>    padding_side=&quot;left&quot;,<br>    add_eos_token=True,<br>    add_bos_token=True,<br>)<br><br>tokenizer.pad_token = tokenizer.eos_token</pre><p>Having the model and aligned tokenizer loaded, let’s head to data. In previous part of this tutorial we focused on generating data, questions and answers, to use for training the model specific task like handling user questions related to legal act. Now, we need to split our data for training and evaluation set. Here, we did this process manually, by splitting the dataset and creating two separate files — training and evaluation datasets. In this case around 80% is training dataset and around 20% is evaluation dataset.</p><pre>train_data_path = &#39;ft_output_data/data_ft_20250130_221652_hq_train.jsonl&#39;<br>eval_data_path = &#39;ft_output_data/data_ft_20250130_221652_hq_eval.jsonl&#39;</pre><pre>train_dataset = load_data(path=train_data_path, type=&#39;train&#39;, format=&#39;json&#39;)<br>eval_dataset = load_data(path=eval_data_path, type=&#39;train&#39;, format=&#39;json&#39;)</pre><p>After loading the data to a specific format suitable for fine-tuning, we need to preprocess the input data to be used for QA task. Our data now will have format appropriate to the model chat template. It will be also tokenized (transformed from words to numbers, according to the chosen tokenizer).</p><pre>tokenized_train_dataset = train_dataset.map(lambda x: generate_with_template(prompt=x, tokenizer=tokenizer))<br>tokenized_eval_dataset = eval_dataset.map(lambda x: generate_with_template(prompt=x, tokenizer=tokenizer))</pre><p>Let us verify how long our sentences are. In the first part of article about data generation, we asked GPT model to deliver answers with a limit of 200 tokens. We set this limit to instruct the model to provide concise answer within this number of tokens. Combining<strong> questions and answers</strong> gives us lengths as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*tCzsbkjA4U3a1MHWRuMPbA.png" /></figure><p>As shown, the majority of sentences are between 250 and 450 tokens in length. Now, for model usage we need to make all the sentences mand make them the same size and if the sentence is shorter we add padding.</p><pre>max_length = 512<br>tokenized_train_dataset = train_dataset.map(lambda x: generate_and_tokenize_with_template(prompt=x, tokenizer=tokenizer, length=max_length))<br>tokenized_val_dataset = eval_dataset.map(lambda x: generate_and_tokenize_with_template(prompt=x, tokenizer=tokenizer, length=max_length))</pre><p>And now plotting the truncated (with padding) version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*bSnC0b5aisZ_kSbRd_zcwA.png" /></figure><p>Data is ready!</p><h3><strong>Fine-tuning preparation</strong></h3><p>At first, let’s create our LORA config. LORA stands for Low-Rank Adaptation which breaks down the original model matrix into the two smaller ones, which drastically reduces the number of parameters which needs to be trained, maintaining quality and efficiency. The most important parameters we will take into consideration is R and alpha. R, for Rank, will determine how many trainable parameters we will train and alpha will determine how much focus we should put on new learned weights, LORA paper suggest that alpha should be 2x Rank. According to FartyPants (yeah, really — <a href="https://medium.com/@fartypantsham/what-rank-r-and-alpha-to-use-in-lora-in-llm-1b4f025fd133)">https://medium.com/@fartypantsham/what-rank-r-and-alpha-to-use-in-lora-in-llm-1b4f025fd133)</a> we should be careful with this parameters as there is a chance that our model base capabilities will be devoured by new ones.</p><p><strong>Disclaimer!</strong> Shown parameters and results are derived from multiple fine-tuning sessions with different parameters and approaches. Please do experiment on this field!</p><p>LORA config:</p><pre>lora_params = {<br>    &#39;r&#39;: 32,<br>    &#39;alpha&#39;: 64,<br>    &#39;layers&#39;: [&quot;q_proj&quot;,<br>            &quot;k_proj&quot;,<br>            &quot;v_proj&quot;,<br>            &quot;o_proj&quot;,<br>            &quot;gate_proj&quot;,<br>            &quot;up_proj&quot;,<br>            &quot;down_proj&quot;,<br>            &quot;lm_head&quot;],<br>    &#39;dropout&#39;: 0.05<br>}<br><br>use_linear_layers = False<br>linear_layers = [&#39;gate_proj&#39;, &#39;down_proj&#39;, &#39;up_proj&#39;, &#39;q_proj&#39;, &#39;v_proj&#39;, &#39;k_proj&#39;,&#39;o_proj&#39;]<br><br>config = LoraConfig(<br>    r=lora_params.get(&#39;r&#39;),<br>    lora_alpha=lora_params.get(&#39;alpha&#39;),<br>    target_modules=lora_params.get(&#39;layers&#39;) if not use_linear_layers else linear_layers,<br>    bias=&quot;none&quot;,<br>    lora_dropout=lora_params.get(&#39;dropout&#39;),<br>    task_type=&quot;CAUSAL_LM&quot;,<br>)<br><br>model = get_peft_model(model, config)</pre><p>Additional setup:</p><pre>model.gradient_checkpointing_enable() # speeds up training on single GPU<br>model = prepare_model_for_kbit_training(model) # prepares model for training</pre><p><strong>Training</strong></p><p>Here, we are using some additional setup for tracking any experiments. We are using Weights and Biases (https://wandb.ai/) as an experiment tracker.</p><pre>project = &quot;legal-finetune&quot;<br>base_model_name = &quot;bielik-v2.3-instruct-11B&quot;<br>params = f&#39;r-{lora_params.get(&quot;r&quot;)}-alpha-{lora_params.get(&quot;alpha&quot;)}&#39;<br>run_name = base_model_name + &quot;-&quot; + project + &quot;-&quot; + params + &#39;-02022025_hq&#39;<br>output_dir = &quot;./&quot; + run_name<br><br>trainer = transformers.Trainer(<br>    model=model,<br>    train_dataset=tokenized_train_dataset,<br>    eval_dataset=tokenized_val_dataset,<br>    args=transformers.TrainingArguments(<br>        output_dir=output_dir,<br>        warmup_steps=2,<br>        per_device_train_batch_size=2,<br>        gradient_accumulation_steps=1,<br>        gradient_checkpointing=True,<br>        max_steps=600,<br>        learning_rate=2.5e-5, <br>        bf16=True,<br>        optim=&quot;paged_adamw_8bit&quot;,<br>        logging_steps=25,<br>        logging_dir=&quot;./logs&quot;,        <br>        save_strategy=&quot;steps&quot;,       <br>        save_steps=25,                <br>        eval_strategy=&quot;steps&quot;, <br>        eval_steps=25,               <br>        do_eval=True,                <br>        report_to=&quot;wandb&quot;,           <br>        run_name=f&quot;{run_name}-{datetime.now().strftime(&#39;%Y-%m-%d-%H-%M&#39;)}&quot;<br>    ),<br>    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),<br>)<br><br>model.config.use_cache = False<br>trainer.train()</pre><p>For sanity, logging of this process has been cleared to provide more readbality on the notebook / article. Nevertheless, a screenshot of an expected output has been done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*kciLcoXquuZ3o8sI1RXNpg.png" /></figure><p>The process didn’t take much time (around 20–30 minutes). Let’s verify which checkpoint is the best one. It is not always the last one! From the above picture we can observe that validation loss started to increase after 500th step. Additionally, Weights amd Biases logged the whole process and after accessing our experiment online, we can see the chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*gfEqw-5FENAuN9yc0OtALA.png" /></figure><p>In such case, we shouldn’t rely on the last checkpoint, but let’s focus on the ones with lower loss — we can definitely pick 500 instead of 600.</p><p>Now is also a time to load not only our base model but also our checkpoint:</p><pre>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_use_double_quant=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16<br>)<br><br>base_model = AutoModelForCausalLM.from_pretrained(<br>    model_name,  <br>    quantization_config=bnb_config,<br>    device_map=&quot;auto&quot;,<br>    trust_remote_code=True<br>)<br><br>eval_tokenizer = AutoTokenizer.from_pretrained(model_name, skip_special_tokens=True)<br><br>ft_model = PeftModel.from_pretrained(base_model, &quot;bielik-v2.3-instruct-11B-legal-finetune-r-32-alpha-64-02022025_hq/checkpoint-500&quot;)</pre><h3><strong>Fine-tuning evaluation — is the new model truly better than base one?</strong></h3><p>For comparison results between non-finetuned model and finetuned one, the validation dataset is created with selected questions related to the topic of consumer rights. Questions and groundtruth answers come from <a href="https://prawakonsumenta.uokik.gov.pl/pytania-i-odpowiedzi/">https://prawakonsumenta.uokik.gov.pl/pytania-i-odpowiedzi/.</a> We switched the source of questions in order to avoid data leakage (using train / eval dataset questions from earlier prepared data). This dataset is not verbose, it contains only 42 questions, but at this point should be enough to verify if the fine-tuning worked. Those questions and answers are prepared by Office of Competition and Consumer Protection in Poland. This gives our validation dataset additional credibility. Let’s see our validation dataset:</p><pre>validation_dataset = get_validation_dataset()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*YjrJP8HjqVfIrsr03tKPsA.png" /></figure><p>Full validation dataset is available on repository.</p><pre>output_col_name = &#39;answer&#39;<br>current_model_eval = validation_dataset.copy()[&#39;question&#39;].drop_duplicates()<br>current_model_eval = current_model_eval.to_frame()<br>current_model_eval[&#39;model_name&#39;] = f&#39;{model_name}_12022025_hq_ft_model&#39;<br><br>current_model_eval[output_col_name] = current_model_eval[&#39;question&#39;].apply(lambda x: pretty_output(generate_with_chat_template(question=x, eval_model=ft_model, eval_tokenizer=eval_tokenizer)))</pre><p>Once having answers from the fine-tuned model, let’s head to the assessment methods. For running the assessment, three metrics has been provided:</p><ul><li>clarity</li><li>coherence</li><li>accuracy</li></ul><p>All those metrics are LLM based metrics with support of GPT4o. Similarly to the first notebook, we instruct the model to provide a rating within a range from 1 (lowest score) to 5 (highest score) and explanation. Explanations are especially useful to get more insights if results are poor or uncertain.</p><pre>metric_name = &#39;clarity&#39;<br>current_model_eval[metric_name] = current_model_eval[output_col_name].apply(lambda x: OpenAIReq(model=&#39;gpt-4o&#39;).call_api_formatted(prompt=PromptBuilder.get_clarity_pl(x)))</pre><pre>metric_name = &#39;coherence&#39;<br>current_model_eval[metric_name] = current_model_eval[output_col_name].apply(lambda x: OpenAIReq(model=&#39;gpt-4o&#39;).call_api_formatted(prompt=PromptBuilder.get_coherence_pl(x)))</pre><pre>metric_name = &#39;accuracy&#39;<br>current_model_eval[metric_name] = current_model_eval.apply(lambda x: OpenAIReq(model=&#39;gpt-4o&#39;).call_api_formatted(prompt=PromptBuilder.get_accuracy_pl(x[&#39;question&#39;], x[output_col_name])), axis=1)</pre><p>And some support function to fetch the score from the GPT answer:</p><pre>current_model_eval[&#39;coherence_score&#39;] = current_model_eval[metric_name].apply(get_score)<br>current_model_eval[&#39;accuracy_score&#39;] = current_model_eval[metric_name].apply(get_score)<br>current_model_eval[&#39;clarity_score&#39;] = current_model_eval[metric_name].apply(get_score)</pre><p>As a next step, we should run the same evaluation for base model (no fine-tuning) and for groundtruth. This step has already been done in the background (outside this notebook / article), so let’s load the results and see what data will be assessed:</p><pre>val_dataset = pd.read_csv(&#39;data/evaluation_results.csv&#39;, sep=&#39;|&#39;)<br>val_dataset[&#39;model_name&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*VhmxGX5ik5WI2W0FdOuZuw.png" /></figure><p>Now let’s reformat the data for better visualization:</p><pre>comparison_df = pd.melt(val_dataset, id_vars=[&#39;model_name&#39;], value_vars=[&#39;coherence_score&#39;,&#39;accuracy_score&#39;, &#39;clarity_score&#39;])</pre><p>And combine all required inputs, colors into one chart:</p><pre>c_palette = load_cmap(&#39;Anemone&#39;,keep_first_n=5).hex<br>sns.set_theme(rc={&#39;figure.figsize&#39;:(11,8.27)})<br><br>box_plot = sns.boxplot(comparison_df, y=&#39;value&#39;, x=&#39;variable&#39;, hue=&#39;model_name&#39;, palette=c_palette)<br>sns.move_legend(box_plot, &quot;upper left&quot;, bbox_to_anchor=(1, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOto4fih8hA-aP0MpzfPUQ.png" /></figure><p>Voila! Our model generated answers almost at the level of groundtruth! Pretty impressive! Also, when we look at the base model, there is a great difference between them. Let’s break this down and see details on differents plots. <strong>Clarity score </strong>as first:</p><pre>sns.displot(val_dataset, x=&quot;clarity_score&quot;, hue=&quot;model_name&quot;, kind=&quot;kde&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*MRezgfxoThTaIpIDfxc0QA.png" /></figure><p><strong>Accuracy score:</strong></p><pre>sns.displot(val_dataset, x=&quot;accuracy_score&quot;, hue=&quot;model_name&quot;, kind=&quot;kde&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWDcjM_8Ft-RPvEru1tvkw.png" /></figure><p>And the last, but not least —<strong> coherence score</strong>:</p><pre>sns.displot(val_dataset, x=&quot;coherence_score&quot;, hue=&quot;model_name&quot;, kind=&quot;kde&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*2nzs_vpwfcsL-0vivWGRqA.png" /></figure><h3><strong>Summary</strong></h3><p>Well, that’s all folks! It has been a real journey through different aspects of working with LLM — starting from preparing semi-synthetic data with GPT, measuring the data quality, finetuning latest polish LLM Bielik and assessing (also using LLM!) its performance in comparison to groundtruth.</p><p>What is worth mentioning, this performance is an effect of many trials which many of them failed miserably. Often quality of the generated data after finetuning was completely unrelevant and even… quite funny. Models instead of producing short and brief answers, generated new tokens based on some polish online forums when somebody asked about legal advice about differnt topic. From this experience I can conclude the following:<br><strong>High quality data is everything (again) — finetuning process can be very fragile for rubbish data. Passing unchecked, unverified rows can lead to bad performance. </strong>Using presented metrics to get score with explanations gave me additional insights what is wrong with prompting and because of this I was able to react and introduce a fix. Data is everything!</p><p>Full code is available on the github repository: <a href="https://github.com/witold87/llm-bielik-ft-legal">https://github.com/witold87/llm-bielik-ft-legal</a></p><h3><strong>References</strong></h3><ol><li><a href="https://arxiv.org/abs/2401.08406">https://arxiv.org/abs/2401.08406</a></li><li><a href="https://arxiv.org/pdf/2106.09685">https://arxiv.org/pdf/2106.09685</a></li><li><a href="https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Mistral/Supervised_fine_tuning_(SFT)_of_an_LLM_using_Hugging_Face_tooling.ipynb">https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Mistral/Supervised_fine_tuning_(SFT)_of_an_LLM_using_Hugging_Face_tooling.ipynb</a></li><li><a href="https://github.com/brevdev/notebooks/blob/main/mistral-finetune-own-data.ipynb">https://github.com/brevdev/notebooks/blob/main/mistral-finetune-own-data.ipynb</a></li><li><a href="https://medium.com/@fartypantsham/what-rank-r-and-alpha-to-use-in-lora-in-llm-1b4f025fd133">https://medium.com/@fartypantsham/what-rank-r-and-alpha-to-use-in-lora-in-llm-1b4f025fd133</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5c4d02c80a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning Bielik LLM from a scratch, part I]]></title>
            <link>https://medium.com/@wpawlak87/fine-tuning-bielik-llm-from-a-scratch-part-i-af4c9916e731?source=rss-e2b3bfa2bcd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/af4c9916e731</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bielik]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Witold Pawlak]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 22:05:26 GMT</pubDate>
            <atom:updated>2025-02-25T08:43:00.339Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Finetuning Bielik (Polish LLM), part I — data generation.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vwdcfcfQwFCwB0BUSS-EA.jpeg" /></figure><h3>Introduction</h3><p>The rise of the Large Language Models is definitely a game changer in approach to AI on various markets and branches — we can observe increased popularity of LLMs in academia, business and agriculture. Working with LLMs became a must-do task for all R&amp;D or business departments in order to acknowledge and adapt upcoming possibilities, to stay competitive and gain business advantage. There are many players who invested milions of USD to build their own Large Language Model and took a part in recent markets challenges by introducing their own solution trained on a different data set or to serve a different task (specialized for example in generation of poems or making a summary). At the beginning, as usual when it comes to innovation at that scale, we are thinking of endless possibilities, what kind of new opportunities we reach without putting much focus on other important factors like costs, maintenance, security, stability. Currently, we have multiple models which are production ready — many work has been done at those fields also making those LLMs more reliable and secured. One of the outcomes from this LLM race is that people noticed that it is good idea to look at smaller models, more specialized in one or two tasks, not the general ones. This specialization also is related to language supported. LLMs are broadly trained on English language data, due to the fact that more than a half of websites content is written in English. Many models, paid and open sourced ones, have different level of quality when it comes to using them with local language. Quite often it occurs that offered quality is not enough to prove the business value for specific use case. This pushed some parties to create smaller models and/or suggested the fine-tuning with data in local language.</p><h3>Goal</h3><p>The goal of this notebook is to finetune a Polish language based LLM called Bielik, developed by SpeakLeash organization (<a href="https://huggingface.co/speakleash/Bielik-11B-v2.3-Instruct">https://huggingface.co/speakleash/Bielik-11B-v2.3-Instruct</a>) with the legal documents. Data is specifically chosen for this task — legal documents are strictly connected to the particular language.</p><p><strong>Important! Main focus of this article is on polish data for polish model. However, those rules and code apply of course on other languages and other models trained on local language.</strong></p><p>Primary concept of legal documents is to be in line with local (Polish in this case) regulations. One of the approaches is to translate documents to English and then used by the LLM. However, legal documents such as purchase agreements or any other agreements are designed by lawyers who understand the legal language nuances. They need to construct documents that are reliable, understandable by many and embedded in Polish law regulations. This requires from LLM to be more specific on many levels — starting from using prevalent data in one language and fine-tuning it to be able to work with more detailed task.</p><h3>Table of content</h3><p>This notebook covers multiple steps:<br> 1. Loading and splitting data into chunks<br> 2. Generating new data (question and answers) for the future fine-tuning<br> 3. Evaluating generated data<br> 4. Selecting the data based on metrics<br> 5. Preparing the output for FT</p><p>Fine tuning itself will be covered later on, in part II.</p><p>Let’s get to work!</p><h3>Loading and working with data</h3><p>For preparing the data we will use <a href="https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU20140000827/U/D20140827Lj.pdf">https://isap.sejm.gov.pl/isap.nsf/download.xsp/WDU20140000827/U/D20140827Lj.pdf</a> . This is polish act about consumer rights. Data has not been chosen randomly — showing LLM possibilities on such legal act can be quite interesting for the broader audience seeking help with understanding the nuances of legal documents. After fine-tuning, model can be used to determine if legal agreement passed by the user contain abusive clauses.</p><p>Let’s start by importing required libraries. Code runs on Python 3.11.</p><pre>import datetime<br>import pandas as pd<br>import numpy as np<br>from dotenv import load_dotenv, find_dotenv<br>import pymupdf<br>import uuid<br>from tqdm.notebook import tqdm<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from src.external_requests.openai_req import OpenAIReq<br>from src.external_requests.prompting import PromptBuilder<br>from src.evaluation.distance_based import DistanceEvaluator<br>from src.evaluation.reporting import Reporting<br>import tiktoken</pre><p>Load your environmental variables using dotenv library. Additionally to load_dotenv, we are using also find_dotenv() method to trigger support for finding the .env file in our project.</p><pre>load_dotenv(find_dotenv())</pre><p>For this use case I am using commonly used splitter — Recursive Character Text Splitter from langchain and PyMuPDF library for parsing the PDF. Document is well formatted and doesn’t contain more complex structures like graphs or tables.</p><blockquote><em>This text splitter is the recommended one for generic text. It is parameterized by a list of characters. It tries to split on them in order until the chunks are small enough. The default list is </em><em>[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;].</em></blockquote><blockquote><em>PyMuPDF is a high-performance Python library for data extraction, analysis, conversion &amp; manipulation of PDF (and other) documents.</em></blockquote><pre>splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=120)<br>path = &#39;data/ustawa_o_prawach_konsumenta.pdf&#39; # name of your file in local file system (after downloading the PDF)<br>all_data = pymupdf.open(path)</pre><p>Let’s split into the document into smaller chunks:</p><pre>all_chunks = []<br>for document in all_data:<br>    text_page = document.get_textpage().extractText()<br>    chunks_per_page = splitter.split_text(text_page)<br>    all_chunks.append(chunks_per_page)<br>        <br>len(all_chunks)</pre><p>Also, let’s define here a helper method for calculating tokens for OpenAI based models. This will be much help later on!</p><pre>def get_number_of_tokens(text:str) -&gt; str:<br>    encoding = tiktoken.get_encoding(&quot;cl100k_base&quot;)<br>    n_tokens = len(encoding.encode(text))<br>    return n_tokens</pre><h3>Generating new data (questions) with a support of GPT 4o-mini</h3><p>For this task the GPT 4o-mini was chosen. GPT has proven itself as a great tool for text generation in many languages and also for assessing own work (this part will be covered later in the article). What is more, it has proven also it’s abilities to generate structured content. In the below code snippet there is one important remark. As presented, there are two similar variables — max_tokens and model_max_tokens. ChatGPT model support tokens limitation during an api call. However, this limitation ca be tricky as it should be considered rather as a cost guard than concise content guard. Setting model’s max tokens to low number results in sentence truncation and losing information. That is the reason the second variable was introduced — max_tokens. Max_tokens variable is passed to the prompt for the model as a part of an instruction to model to instruct the model to generate succinct yet comprehensive answer within the given token limit.</p><pre>model_version = &#39;gpt-4o-mini&#39;<br>all_data = []<br>max_tokens = 500<br>model_max_tokens = int(max_tokens + (max_tokens*0.20))<br>for i, page in tqdm(enumerate(all_chunks)):<br>    page_id = str(uuid.uuid4())<br>    for chunk in enumerate(page):<br>        nth_chunk, text_chunk = chunk<br>        generated_questions = OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.generate_questions(n_questions=4, text=chunk, tokens=max_tokens),<br>                                                   temperature=0.1,max_tokens=model_max_tokens)<br>        data = {&#39;chunk_id&#39;: f&#39;{page_id}_{nth_chunk}&#39;, <br>                &#39;text_chunk&#39;: text_chunk,<br>                &#39;page_id&#39;: page_id,<br>                &#39;generated_questions&#39;: generated_questions}<br>        all_data.append(data)</pre><p>Let’s do some data cleaning and validating. We need a helper method to do required data preparation with validation on null values:</p><pre>def process_df_with_questions(data: pd.DataFrame) -&gt; pd.DataFrame:<br>    data[&#39;questions_splitted&#39;] = data[&#39;generated_questions&#39;].str.split(&#39;\n&#39;)<br>    data = data.explode(&#39;questions_splitted&#39;)<br>    data = data[~data[&#39;questions_splitted&#39;].isna()]<br>    data[&#39;questions_splitted&#39;]  = data[&#39;questions_splitted&#39;].replace(r&#39;^\s*$&#39;, np.nan, regex=True)<br>    return data<br>df = process_df_with_questions(data=df)<br>df = df[~df[&#39;questions_splitted&#39;].isna()]<br>df[&#39;questions_splitted&#39;].isna().sum()</pre><p>The expected result from the last line should be 0 of course.</p><h3>Fetching answers for generated questions based on the text chunk</h3><p>In the next step we are also generating text, but in this case we are focusing on answers to the previously generated questions. As in previous example, we also introduce a token limitation for the model, and it is passed to the prompt as part of the instruction. In this case we want to limit the answer length in order to get concise and precise answer as it is quite often expected from LLM to deliver brief answers. To support that, we set the temperature as low as possible.</p><pre>answer_tokens = 200<br>df[f&#39;answer_{answer_tokens}&#39;] = df.apply(lambda x: OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.get_answers_based_on_text_and_questions(text=x[&#39;text_chunk&#39;], question= x[&#39;questions_splitted&#39;], tokens=answer_tokens), temperature=0.0), axis=1)</pre><p>To validate if GPT “listened” to our instruction with token limitation, let’s count tokens and plot the histogram. As shown, the model generated answer mostly within the range of 100–300 tokens:</p><pre>df[&#39;n_tokens_ans_200&#39;] = df[&#39;answer_200&#39;].apply(lambda x: get_number_of_tokens(text=x))<br>pd.plotting.hist_series(df[&#39;n_tokens_ans_200&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*kUxRCkM83gqTX1oG9ZmMSA.png" /><figcaption>Number of sentences (Y-axis) and corresponding number of tokens (X-axis).</figcaption></figure><p>Now, having chunks, questions and answers for our question, we can continue validating our results.</p><h3>Verifying the quality of generated answers and questions based on selected metrics</h3><p>To verify the quality of our text generation in relation to text chunk there are couple metrics we can use:</p><ul><li>Coverage</li><li>Coherence (Consistency)</li><li>Diversity (based on Word Mover Distance)</li><li>Relevance</li><li>Global relevance</li></ul><p>Majority of the metrics are based on the LLM own capability to assess it’s own work. This has been proven and it is often used in various evaluation frameworks like RAGAS.</p><p>Here metrics are chosen carefully based on article from Microsoft — <a href="https://arxiv.org/abs/2401.08406">https://arxiv.org/abs/2401.08406</a></p><p>Briefly, we can describe the metrics in the way prompt instruction is constructed:</p><ul><li>coverage — Your task is to rate from 1 to 5 if the question can be extracted from the context.</li><li>coherence — Your task is to rate from 1 to 5 the coherence (fluency) of the question and provide explanation.</li><li>relevance — Your task is to rate from 1 to 5 if the provided question could be asked by a lawyer then rate 5, and rate 1 if not based on the question and context.</li><li>global relevance — Your task is to rate from 1 to 5 if the provided question could be asked by a lawyer then rate 5, and rate 1 if not based on the question.</li><li>diversity — not LLM based metric. To calculate this we used Word Mover Distance (WMD). Check <a href="https://radimrehurek.com/gensim/auto_examples/tutorials/run_wmd.html">https://radimrehurek.com/gensim/auto_examples/tutorials/run_wmd.html</a> for more details.</li></ul><p>Let’s apply those metrics and verify results.</p><p><strong>Coverage rating:</strong></p><pre>df[&#39;coverage_rating&#39;] = df.apply(lambda x: OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.get_coverage(question=x[&#39;questions_splitted&#39;], context=x[&#39;text_chunk&#39;])), axis=1)<br>pd.plotting.hist_series(df[&#39;coverage_rating&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*bTs3IIgc_sEj_-tVCYQXMg.png" /><figcaption>Number of sentences (Y-axis) and corresponding rating for coverage (X-axis).</figcaption></figure><p><strong>Coherence rating:</strong></p><pre>df[&#39;coherence_pl&#39;] = df[&#39;questions_splitted&#39;].apply(lambda x: OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.get_coherence_pl(x)))</pre><p>For coherence we asked the GPT also for explanation to understand the results given by the model:</p><pre>df[[&#39;coherence_rate_pl&#39;, &#39;coherence_expl_pl&#39;]] = df.coherence_pl.str.split(&#39;|&#39;, n=1,  expand=True)</pre><p>Compare the results and verify if there is a difference between English and Polish prompt:</p><pre>pd.plotting.hist_series(df[&#39;coherence_rate_pl&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*KTOmges97-E_BcAU9XPbZA.png" /><figcaption>Number of sentences (Y-axis) and corresponding rating for coherence (X-axis).</figcaption></figure><p>Lower results (high number of 3) can be indication that for coherence (fluency) model was not able to generate perfect questions or finds it difficult to make proper assessment due to specific language (legal).</p><p>In data science area the data is everything — and good quality data is priceless. That is the reason, I spent some time on investigation why the data was so bad. I did small prompt engineering to boost the results and select only those rows which values in assessment are high enough to proceed. After this process, I ended up with ~730 records with high quality data. Full code is available here: <a href="https://github.com/witold87/llm-bielik-ft-legal/blob/feature/article/src/llm-bielik-ft-data-generation-part-I.ipynb">https://github.com/witold87/llm-bielik-ft-legal/blob/feature/article/src/llm-bielik-ft-data-generation-part-I.ipynb</a></p><p><strong>Relevance rating:</strong></p><pre>df[&#39;relevance&#39;] = df.apply(lambda x: OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.get_relevance(question=x[&#39;questions_splitted&#39;], context=x[&#39;text_chunk&#39;])),axis=1)<br>pd.plotting.hist_series(df[&#39;relevance&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*XDu9cMx8L52k2K2Ys-9M8A.png" /><figcaption>Number of sentences (Y-axis) and corresponding rating for relevance (X-axis).</figcaption></figure><p><strong>Global relevance:</strong></p><pre>df[&#39;global_relevance&#39;] = df.apply(lambda x: OpenAIReq(model=model_version).call_api(prompt=PromptBuilder.get_global_relevance(question=x[&#39;questions_splitted&#39;])),axis=1)<br>pd.plotting.hist_series(df[&#39;global_relevance&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Z4H6s2Xupc18d0r7XpdGzg.png" /><figcaption>Number of sentences (Y-axis) and corresponding rating for global relevance (X-axis).</figcaption></figure><p>Last, but not least, distance with WMD. Instantiate the object designed for calculating Word’s Mover Distance and check the question to answer distance:</p><pre>dist_evaluator = DistanceEvaluator()<br>df[f&#39;wmd_question_answer_200&#39;] = df.apply(lambda x: dist_evaluator.get_diversity_by_wmd(x[&#39;questions_splitted&#39;], x[f&#39;answer_{answer_tokens}&#39;]), axis=1)<br>pd.plotting.hist_series(df[&#39;wmd_question_answer_200&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*2sHjcZ7XfwXrD0R7bC0RZg.png" /><figcaption>Number of sentences (Y-axis) and corresponding distance for question-answer (X-axis).</figcaption></figure><p>When it comes to distance, WMD measures the distance in range from 0 to 1, where 0 means that sentences are close to each other and 1, where sentences are more far away.</p><p>Next, let’s check chunk to question distance:</p><pre>df[&#39;wmd_chunk_question&#39;] = df.apply(lambda x: dist_evaluator.get_diversity_by_wmd(x[&#39;text_chunk&#39;], x[&#39;questions_splitted&#39;]), axis=1)<br>pd.plotting.hist_series(df[&#39;wmd_chunk_question&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*KSGfafNktfL8PWQVflHF6A.png" /><figcaption>Number of sentences (Y-axis) and corresponding distance between chunk and question (X-axis).</figcaption></figure><p>To have better visibility, we can calculate the mean and standard deviation of our results:</p><pre>mean_wmd_qch = df[&#39;wmd_chunk_question&#39;].mean()<br>std_wmd_qch = df[&#39;wmd_chunk_question&#39;].std()<br>print(f&#39;Mean for question to chunk for WMD is {mean_wmd_qch} with std as {std_wmd_qch}&#39;)</pre><p>Mean for question to chunk for WMD is 0.18 with std as 0.06. When we calculate the same for question to answer with…</p><pre>mean_wmd_qa = df[&#39;wmd_question_answer_200&#39;].mean()<br>std_wmd_qa = df[&#39;wmd_question_answer_200&#39;].std()<br>print(f&#39;Mean for question to answer for WMD is {mean_wmd_qa} with std as {std_wmd_qa}&#39;)</pre><p>…we get mean for <strong>question to answer</strong> at 0.14 with std as 0.043.</p><p>There is still one calculation to be done (yes, you guessed right — question to question). However, for this we need to create so-called similarity matrix to compare each question to another. This is covered in this snippet:</p><pre>reporting = Reporting(data=df)<br>sim_matrix = reporting.create_similarity_matrix_for_wmd(on_column=&#39;questions_splitted&#39;)<br>std, mean = reporting.get_summary_for_wmd(sim_matrix)<br>print(f&#39;Mean for question to question for WMD is {mean} with std as {std}&#39;)</pre><p>For question to question distance we get mean at 0.23 and std at 0.05. If this expected result? We would say so — the distance between questions is the biggest one because in our legal act we asked about different topics and they may vary between particular paragraphs. Still, we have a confirmation that our dataset is concise.</p><h3>Evaluation Summary</h3><p>From the results we can conclude that GPT4o-mini prepared for us quite good dataset — majority of values are high (low in terms of similarity). The only outlier in those results is the coherence score but after prompt tuning and filtering out records with low results we are good to go.</p><p>Overall, the results have proven that generated question with support of GPT4o-mini model are good enough to use them as the input instructions for the model. Now, question value pairs will be transformed into the proper structure to be later on used for fine tuning.</p><h3>Data preparation for fine-tuning</h3><pre>qa_df_200 = df[[&#39;questions_splitted&#39;, &#39;answer_200&#39;]]<br>qa_df_200 = qa_df_200.rename(columns={&#39;questions_splitted&#39;: &#39;question&#39;, &#39;answer_200&#39;: &#39;answer&#39;})<br><br>qa_df_200 = qa_df_200.sample(frac=1) # shuffling the data<br><br>now = datetime.datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)<br>with open(f&#39;ft_output_data/data_ft_{now}.jsonl&#39;, &quot;w&quot;) as f:<br>    f.write(qa_df_200.to_json(orient=&#39;records&#39;, lines=True, force_ascii=False))</pre><h3>Summary</h3><p>As our last piece of code is executed, we can finish first part of this article series — data preparation. I hope you enjoyed it as much as me! Let’s move on to the second part of the fine-tuning polish LLM model with our generated data. All code is placed on GitHub at: <a href="https://github.com/witold87/llm-bielik-ft-legal/tree/main">https://github.com/witold87/llm-bielik-ft-legal/tree/main</a>.</p><p>See ya!</p><h3>References and sources</h3><ul><li><a href="https://arxiv.org/abs/2401.08406">https://arxiv.org/abs/2401.08406</a></li><li><a href="https://www.statista.com/statistics/262946/most-common-languages-on-the-internet/">https://www.statista.com/statistics/262946/most-common-languages-on-the-internet/</a></li><li><a href="https://medium.com/@bijit211987/the-rise-of-small-language-models-efficient-customizable-cb48ddee2aad">https://medium.com/@bijit211987/the-rise-of-small-language-models-efficient-customizable-cb48ddee2aad</a></li><li><a href="https://python.langchain.com/docs/how_to/recursive_text_splitter/">https://python.langchain.com/docs/how_to/recursive_text_splitter/</a></li><li><a href="https://radimrehurek.com/gensim/auto_examples/tutorials/run_wmd.html">https://radimrehurek.com/gensim/auto_examples/tutorials/run_wmd.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af4c9916e731" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>