<?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 Erfan zare Chavoshi on Medium]]></title>
        <description><![CDATA[Stories by Erfan zare Chavoshi on Medium]]></description>
        <link>https://medium.com/@erfanzare810?source=rss-ed12cdda2526------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1F4U2j2yI3ktFQmFh7NzBA.jpeg</url>
            <title>Stories by Erfan zare Chavoshi on Medium</title>
            <link>https://medium.com/@erfanzare810?source=rss-ed12cdda2526------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:42:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erfanzare810/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[vInference: Accelerating Large Language Model Inference with EasyDeL]]></title>
            <link>https://medium.com/@erfanzare810/vinference-accelerating-large-language-model-inference-with-easydel-5b1d8bb7419f?source=rss-ed12cdda2526------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1d8bb7419f</guid>
            <category><![CDATA[inference-engine]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Erfan zare Chavoshi]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 01:29:28 GMT</pubDate>
            <atom:updated>2025-03-11T01:29:28.442Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s rapidly evolving AI landscape, the need for efficient inference is paramount. vInference, the inference engine within the EasyDeL framework, is designed to meet this challenge head-on. Whether you’re deploying models on cutting-edge TPUs or everyday GPUs, vInference delivers high-performance inference without compromising on flexibility or scalability.</p><p><strong>Long-Context Efficiency</strong></p><p>Our system processes 65,536~131,072-token sequences efficiently, making extended context windows practical for real-world applications while maintaining reasonable response times.</p><h3><strong>What is vInference?</strong></h3><p>vInference is EasyDeL’s specialized inference solution engineered for large language models (LLMs) / (LVM) or other models. Built on a modern Flax NNX architecture, it provides:</p><p>- <strong>OpenAI-compatible API endpoints </strong>that integrate seamlessly with your existing applications.</p><p>- <strong>Platform flexibility</strong> by supporting Triton, XLA, and Pallas backends.</p><p>- <strong>Advanced quantization techniques</strong> (including NF4, A8BIT, A8Q, and A4Q) for efficient memory and compute usage.</p><p>- <strong>Dynamic configuration</strong> options that allow performance to be fine-tuned for various hardware setups.</p><p>Moreover, EasyDeL supports over 100+ different model variants — making vInference a truly versatile solution for everything from traditional Transformers to emerging architectures.</p><h3>Key Advantages</h3><p><strong>Hardware Flexibility</strong></p><p>Although our benchmarks were executed on a TPUv4–8, vInference’s design ensures compatibility with virtually any computing device. This adaptability means you can seamlessly transition from local testing on a single GPU to scaling up on a multi-device cluster in the cloud.</p><p><strong>Scalability</strong></p><p>vInference’s architecture is built for horizontal scalability. There is no hard limit on the number of devices you can use, making it a future-proof solution for high-demand inference scenarios. As your deployment scales, vInference continues to deliver consistent, high-performance results.</p><p><strong>Model Compatibility</strong></p><p>With support for over 100 model variants, vInference offers an incredibly versatile platform. This compatibility extends from language models to vision models, ensuring that regardless of your AI application, there’s a configuration that fits.</p><h3><strong>Benchmarking on TPUv4–8</strong></h3><p>Our benchmark tests were conducted on a single TPUv4–8, showcasing the engine’s impressive capabilities. Importantly, vInference is not bound to a single hardware setup. It can be deployed on any device — whether consumer-grade GPUs or large-scale TPU clusters — with no inherent scaling limitations. This means you can start small and expand horizontally as your needs grow.</p><p><strong>Benchmark Configuration</strong></p><p>- <strong>Model:</strong> 7B (Qwen 2.5)</p><p>- <strong>Prefill Sizes:</strong> 8,192; 16384; 32768; 65536; 131072 tokens</p><p>- <strong>Max New Tokens: </strong>2,048, 4,096 and 8,192 tokens</p><p>The following visualizations highlight various aspects of performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKZLbiiVB0rYEA3xyZWH3A.png" /></figure><p><strong>Time Heatmap:</strong> Illustrates how inference time changes across different prefill sizes and max new tokens configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MIEEpJ7sWyHgFGGtNvTMw.png" /></figure><p><strong>TPS 3D Surface:</strong> Provides a comprehensive three-dimensional view of tokens per second (TPS) across the tested parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ5CXmW8nd3EIvB9WOgVGA.png" /></figure><p><strong>TPS Heatmap:</strong> Offers a clear, visual comparison of performance, pinpointing optimal configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1U7qLk_-a_nKnG-puseIw.png" /></figure><p><strong>TPS vs Max New Tokens:</strong> Demonstrates the relationship between the number of tokens generated and overall throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IHjsPeIw1KdymBPsJuAtg.png" /></figure><p><strong>TPS vs Prefill:</strong> This shows how throughput is affected by different prefill sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWBAEjFO7lutrMK0INl_dA.png" /></figure><p><strong>TPS Variation Boxplot:</strong> Shows the consistency of performance across runs for each configuration. Configurations are sorted by average TPS, with boxplots revealing median performance (middle line), variability (box height), and outliers (points). Shorter boxes indicate more consistent performance, making it easier to identify configurations that are both fast and reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2ARHwJ-4QTl6Vl04BJFpg.png" /></figure><p><strong>Prefill Ratio Heatmap:</strong> Displays what percentage of total processing time is spent on prefill versus generation. The color scale shows where time is being spent — warmer colors indicate prefill dominance, and cooler colors show efficient generation. This helps optimize real-world workloads by revealing whether to focus on reducing context processing overhead or improving token generation speed.</p><p>Each of these plots offers unique insights into the operational efficiency of vInference, making it easier to optimize performance based on your specific application needs.</p><h3><strong>Getting Started</strong></h3><p>Setting up vInference is simple. Install EasyDeL via pip:</p><pre>pip install easydel==0.1.0 -U<br>pip install torch --index-url https://download.pytorch.org/whl/cpu  # Required for model conversion<br>pip install jax[tpu] -U</pre><p>Then, integrate it with your model using a few lines of code</p><h4>Configuration Setup</h4><pre>import easydel as ed<br>from transformers import AutoTokenizer<br>import jax.numpy as jnp<br><br># Sharding Dimensions (Data Parallel, FSDP, Tensor Parallel, Sequence Parallel)<br>sharding_axis_dims = (1, 1, 1, -1)  # -1 = auto <br><br># Context Handling<br>max_length = 2**16  # 65k context<br>max_new_tokens = 2**12  # 4k generation<br><br># Model Setup<br>pretrained_model_name_or_path = &quot;Qwen/Qwen2.5-7B-Instruct-1M&quot;<br>dtype = param_dtype = jnp.bfloat16  # Memory-efficient float type</pre><h4>Tokenizer Initialization</h4><pre>tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path)<br>tokenizer.padding_side = &quot;left&quot;<br>tokenizer.pad_token_id = tokenizer.eos_token_id</pre><h4>Model Loading with Smart Sharding</h4><pre>model = ed.AutoEasyDeLModelForCausalLM.from_pretrained(<br>    pretrained_model_name_or_path,<br>    auto_shard_model=True,  # Automatic distributed sharding<br>    sharding_axis_dims=sharding_axis_dims,<br>    config_kwargs=ed.EasyDeLBaseConfigDict(<br>        freq_max_position_embeddings=max_length + max_new_tokens,<br>        mask_max_position_embeddings=max_length + max_new_tokens,<br>        kv_cache_quantization_method=ed.EasyDeLQuantizationMethods.NONE,<br>        attn_dtype=dtype,<br>        attn_mechanism=ed.AttentionMechanisms.AUTO,  # Chooses optimal attention<br>        blocksize_q=1024,  # Memory block size for attention<br>        blocksize_k=1024<br>    ),<br>    quantization_method=ed.EasyDeLQuantizationMethods.NONE,<br>    param_dtype=param_dtype,<br>    dtype=dtype<br>)</pre><h4>Inference Configuration</h4><pre>inference = ed.vInference(<br>    model=model,<br>    processor_class=tokenizer,<br>    generation_config=ed.vInferenceConfig(<br>        max_new_tokens=max_new_tokens,<br>        temperature=0.7,   # Creativity control<br>        do_sample=True,    # Enable probabilistic sampling<br>        top_p=0.95,        # Nucleus sampling<br>        top_k=10,          # Top-k filtering<br>        eos_token_id=model.generation_config.eos_token_id,<br>        streaming_chunks=32,  # For partial output streaming<br>        num_return_sequences=1<br>    )<br>)<br><br># Pre-compile for faster first response<br>inference.precompile(1, max_length)</pre><h4>Launch API Server</h4><pre>api_server = ed.vInferenceApiServer({inference.inference_name: inference})<br>api_server.fire()  # Starts server</pre><p>This code snippet sets up a basic inference server that is OpenAI API-compatible, enabling rapid deployment and integration.</p><h3><strong>Future Directions</strong></h3><p>The journey doesn’t stop here. Future enhancements include:</p><p>- <strong>Broader Model Architecture Support:</strong> Extending compatibility to even more model types.</p><p>- <strong>Enhanced Distributed Inference:</strong> Improving multi-device collaboration for ultra-high-performance applications.</p><p>- <strong>Optimized Quantization Techniques:</strong> Pushing the boundaries of efficiency for even faster inference or training.</p><p>- <strong>Hardware-Specific Optimizations:</strong> Fine-tuning configurations to extract maximum performance from every compute resource.</p><p><strong>Special Thanks to the Flax NNX Team</strong></p><p>A special thanks to the Flax NNX team for their exceptional framework, which combines <strong>modular design</strong> and <strong>runtime flexibility</strong>. NNX’s API has been pivotal in enabling EasyDeL to deliver high-performance runtime while maintaining ease of customization for diverse deployment scenarios.</p><h3><strong>Conclusion</strong></h3><p>vInference marks a significant step forward in LVM/LLM inference, delivering a blend of flexibility, efficiency, and scalability that meets the demands of modern AI applications. With its hardware-agnostic design, robust scalability, and broad model compatibility, vInference is well-positioned to serve as the backbone for next-generation AI deployments.</p><p>Explore vInference today and see how EasyDeL is redefining the future of efficient, scalable model inference.</p><p>For more details, visit the <a href="https://easydel.readthedocs.io/en/latest/">EasyDeL Documentation</a> or check out the <a href="https://github.com/erfanzar/EasyDeL">GitHub repository</a>. If you have any questions or would like to contribute, feel free to reach out at erfanzare810@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1d8bb7419f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Model Adaptation: A Deep Dive into Supervised Fine-Tuning with EasyDeL using JAX on TPUs…]]></title>
            <link>https://medium.com/@erfanzare810/mastering-model-adaptation-a-deep-dive-into-supervised-fine-tuning-with-easydel-using-jax-on-tpus-4f38f55d3088?source=rss-ed12cdda2526------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f38f55d3088</guid>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Erfan zare Chavoshi]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 17:57:46 GMT</pubDate>
            <atom:updated>2024-04-12T17:57:46.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Model Adaptation: A Deep Dive into Supervised Fine-Tuning with EasyDeL using JAX on TPUs and GPUs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXkdo5QSBsd0GuGETqaIdA.png" /></figure><h3>Introduction</h3><p>Supervised Fine-Tuning of LLMs, or Language Model Pretraining, involves training a large language model on a specific task or domain by providing it with labeled data. This process typically starts with a pre-trained language model (LLM) that has been trained on a large corpus of text data, such as GPT (Generative Pre-trained Transformer) models.</p><p>Fine-tuning involves further training the model on a smaller dataset that is specific to the task at hand. For example, if you wanted to train a language model to generate news headlines, you would fine-tune a pre-trained LLM on a dataset of news headlines with their corresponding categories or topics.</p><p>In the ever-evolving landscape of artificial intelligence and natural language processing, the ability to fine-tune pre-trained language models (LLMs) for specific tasks has become indispensable. Supervised fine-tuning, in particular, stands out as a powerful technique, enabling LLMs to excel in diverse applications ranging from sentiment analysis to language translation. However, the process of fine-tuning can be complex, requiring efficient tools and computational resources to achieve optimal results.</p><p>Enter <a href="https://github.com/erfanzar/EasyDeL">EasyDeL</a>, Leveraging the power of JAX and harnessing the computational prowess of TPUs (Tensor Processing Units) and GPUs (Graphics Processing Units), <a href="https://github.com/erfanzar/EasyDeL">EasyDeL </a>revolutionizes how developers and researchers approach model adaptation. In this article, we embark on a journey to explore the depths of supervised fine-tuning with <a href="https://github.com/erfanzar/EasyDeL">EasyDeL</a>, uncovering its capabilities, advantages, and real-world applications.</p><h3><strong>Coding</strong></h3><p>Noting Beats coding to let jump into coding and Fine-Tuning Gemma-2B-it with <a href="https://github.com/erfanzar/EasyDeL">EasyDeL</a></p><blockquote>The Following Code is being executed in Kaggle TPU notebooks so everybody can easily try the code out and you can also try bigger models and anyother model that you want since <a href="https://github.com/erfanzar/EasyDeL">EasyDeL </a>support most of the LLMs like Mixtral, Qwen2, JetMoE, StableLM, PHI …</blockquote><pre>pip install fjformer datasets gradio wandb sentencepiece transformers -U -q<br>pip install jax[tpu]==0.4.22 -f https://storage.googleapis.com/jax-releases/libtpu_releases.html -q<br>pip install git+https://github.com/erfanzar/EasyDeL.git -U -q<br>pip install tensorflow --upgrade -q<br>python -c &quot;from huggingface_hub.hf_api import HfFolder; HfFolder.save_token(&#39;&lt;HF_TOKEN&gt;&#39;)&quot; <br>wandb login &lt;WANDB_TOKEN&gt;<br>apt-get update &amp;&amp; apt-get upgrade -y -q &amp;&amp; apt-get install golang -y -q</pre><p>Now we import what we need to import</p><pre>from EasyDel import (<br>    AutoEasyDelModelForCausalLM,<br>    TrainArguments,<br>    EasyDelOptimizers,<br>    EasyDelSchedulers,<br>    EasyDelGradientCheckPointers,<br>    EasyDelState,<br>    EasyDeLXRapTureConfig,<br>    get_modules_by_type,<br>    easystate_to_huggingface_model,<br>    SFTTrainer,<br>    conversations_formatting_function<br>)<br>from datasets import load_dataset<br>from flax.core import FrozenDict<br>from transformers import AutoTokenizer<br>from jax import numpy as jnp, sharding<br>import jax<br>from transformers import AutoConfig<br>from huggingface_hub import HfApi, hf_hub_download<br>import os<br>import datasets<br>import re<br><br>PartitionSpec = sharding.PartitionSpec<br>api = HfApi()</pre><p>Specifying the arguments of Model</p><pre>sharding_axis_dims = (1, -1, 2, 1) <br># Im using this sharding stragedy but you can go with (1, -1, 1, 1)<br><br>max_length = 2048<br>input_shape = (1, max_length)<br><br>pretrained_model_name_or_path = &quot;google/gemma-2b-it&quot;<br>pretrained_model_name_or_path_tokenizer = &quot;google/gemma-2b-it&quot;<br>new_repo_id = &quot;SFT-Gemma-2B-EasyDeL&quot;<br><br>dtype = jnp.bfloat16<br>use_lora = False<br>block_size = 512<br>model_use_tie_word_embedding = True</pre><p>Loading Model and tokenizer</p><pre>model, params = AutoEasyDelModelForCausalLM.from_pretrained(<br>    pretrained_model_name_or_path,<br>    device = jax.devices(&#39;cpu&#39;)[0],<br>    input_shape = input_shape,<br>    device_map = &quot;auto&quot;,<br>    sharding_axis_dims = sharding_axis_dims,<br>    config_kwargs=dict(<br>        use_scan_mlp=False # Make sure to set this as True<br>    )<br>)<br><br>config = model.config<br>model_parameters = FrozenDict({&quot;params&quot; : params})<br><br>tokenizer = AutoTokenizer.from_pretrained(<br>    pretrained_model_name_or_path_tokenizer,<br>    trust_remote_code=True<br>)<br><br>config.add_basic_configurations(<br>    attn_mechanism=&quot;normal&quot;, # Flash attention is supported too, you can read Docs<br>    block_b=1,<br>    block_q=block_size,<br>    block_k=block_size,<br>    block_k_major=block_size,<br>    shard_attention_computation=True<br>)<br><br>configs_to_initialize_model_class={<br>    &quot;config&quot; : config,<br>    &quot;dtype&quot; : dtype,<br>    &quot;param_dtype&quot; : dtype,<br>    &quot;input_shape&quot; : input_shape<br>}<br><br>if tokenizer.pad_token == None:<br>    tokenizer.pad_token = tokenizer.eos_token<br>    <br>rapture_config = EasyDeLXRapTureConfig(<br>    model_parameters,<br>    lora_dim=64,<br>    fully_fine_tune_parameters=[&quot;embed_tokens&quot;],<br>    lora_fine_tune_parameters=[&quot;q_proj&quot;, &quot;v_proj&quot;, &quot;k_proj&quot;, &quot;o_proj&quot;],<br>    verbose=True<br>) if use_lora else None</pre><p><strong>Loading Dataset</strong></p><p>in the case of using the dataset, you can use whatever you want, I&#39;ll go with <strong><em>HuggingFaceH4/deita-10k-v0-sft.</em></strong></p><pre>dataset_train = load_dataset(<br>    &quot;HuggingFaceH4/deita-10k-v0-sft&quot;,<br>    split=&quot;train_sft&quot;<br>) <br>print(dataset_train)</pre><p>since the Gemma model chat template doesn’t support the system role in their Jinja template we will edit the template a little bit</p><pre>tokenizer.chat_template = &quot;{{ bos_token }}{% for message in messages %}{% if (message[&#39;role&#39;] == &#39;assistant&#39;) %}{% set role = &#39;model&#39; %}{% else %}{% set role = message[&#39;role&#39;] %}{% endif %}{{ &#39;&lt;start_of_turn&gt;&#39; + role + &#39;\n&#39; + message[&#39;content&#39;] | trim + &#39;&lt;end_of_turn&gt;\n&#39; }}{% endfor %}{% if add_generation_prompt %}{{&#39;&lt;start_of_turn&gt;model\n&#39;}}{% endif %}&quot;</pre><p>All of the EasyDeL models contain their unique sharding strategies and I want to show you some customization tricks I&#39;ll change the model partition rules</p><pre>rules = (<br>    (&#39;model/embed_tokens/embedding&#39;, PartitionSpec(&quot;tp&quot;,(&#39;fsdp&#39;, &#39;sp&#39;),)),<br>    (&#39;self_attn/(q_proj|k_proj|v_proj)/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;self_attn/o_proj/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;mlp/gate_proj/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;mlp/down_proj/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;mlp/up_proj/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;input_layernorm/kernel&#39;, PartitionSpec(None,)),<br>    (&#39;post_attention_layernorm/kernel&#39;, PartitionSpec(None,)),<br>    (&#39;model/norm/kernel&#39;, PartitionSpec(None,)),<br>    (&#39;lm_head/kernel&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),&quot;tp&quot;)),<br>    (&#39;.*&#39;, PartitionSpec((&#39;fsdp&#39;, &#39;sp&#39;),))<br>)<br><br>config.get_partition_rules = lambda _: rules </pre><p>Specify the Trainer Arguments</p><pre>train_arguments = TrainArguments(<br>    model_class=get_modules_by_type(config.model_type)[1],<br>    configs_to_initialize_model_class=configs_to_initialize_model_class,<br>    custom_rule=config.get_partition_rules(True),<br>    <br>    num_train_epochs=1,<br>    learning_rate=4e-5,<br>    learning_rate_end=2e-6,<br>    warmup_steps=100,<br>    optimizer=EasyDelOptimizers.ADAMW,<br>    scheduler=EasyDelSchedulers.WARM_UP_COSINE,<br>    weight_decay=0.02,<br>    total_batch_size=40,<br>    max_sequence_length=max_length, <br>    gradient_checkpointing=EasyDelGradientCheckPointers.NOTHING_SAVEABLE,<br>    sharding_array=sharding_axis_dims,<br>    use_pjit_attention_force=False,<br>    gradient_accumulation_steps=1,<br>    <br>    init_input_shape=input_shape,<br>    dtype=dtype,<br>    param_dtype=dtype,<br>    step_start_point=0,<br>    <br>    model_name=&quot;SFT-Gemma&quot;,<br>    training_time=&quot;6H&quot;,<br>    force_batch_and_gradient_accumulation_steps_calculation=False,<br>    rapture_config=rapture_config,<br>)</pre><p>EasyDeL supports many options, if you want to check for more features you can read the Docs.</p><pre>trainer = SFTTrainer(<br>    arguments=train_arguments,<br>    train_dataset=dataset_train,<br>    eval_dataset=None, <br>    # you can use a dataset for evaluation too if you want but make sure <br>    # to set do_eval to True in TrainArguments<br>    tokenizer=tokenizer,<br>    dataset_text_field=None,<br>    formatting_func=lambda x:[conversations_formatting_function(tokenizer, messages_field=&quot;messages&quot;)(x)],<br>    packing=False,<br>    num_of_sequences=max_length,<br>)</pre><p>Start Training the Model</p><pre>output = trainer.train(<br>    model_parameters=model_parameters if not use_lora else None,<br>    state=None<br>) # Trains the Model<br><br>api.create_repo(new_repo_id, private=True, exist_ok=True)<br>api.upload_file(<br>    path_or_fileobj=output.checkpoint_path,<br>    repo_id=new_repo_id,<br>    path_in_repo=output.last_save_file_name<br>) # Upload Model .easy file to huggingface</pre><p>Convert Model Back to Torch for other uses</p><pre>import transformers <br><br><br>with jax.default_device(jax.devices(&quot;cpu&quot;)[0]):<br>    state = EasyDelState.load_state(<br>        output.checkpoint_path,<br>        input_shape=(8, 1),<br>    )<br>    <br>    if model_use_tie_word_embedding:<br>        state_new_params = {<br>            &quot;params&quot; : state.params[&quot;params&quot;] | {<br>                &quot;lm_head&quot; : {<br>                    &quot;kernel&quot; : state.params[&quot;params&quot;][&quot;model&quot;][&quot;embed_tokens&quot;][&quot;embedding&quot;].T<br>                }<br>            }<br>        }<br><br>        state = state.replace( params = state_new_params )<br><br>config = AutoConfig.from_pretrained(pretrained_model_name_or_path)<br><br>with jax.default_device(jax.devices(&quot;cpu&quot;)[0]):<br>    model = easystate_to_huggingface_model(<br>        state=state,<br>        base_huggingface_module=transformers.GemmaForCausalLM,<br>        config=config<br>    ) # Here&#39;s your PyTorch Model<br>     <br>half_model = model.half()<br><br>tokenizer.push_to_hub(new_repo_id)<br>half_model.push_to_hub(new_repo_id)</pre><p>Done! you have trained your model using EasyDeL and you could use LoRA too if you want just by setting use_lora to True</p><h3>Conclusion</h3><p>As we conclude our exploration of supervised fine-tuning with EasyDeL, it’s evident that the landscape of model adaptation is undergoing a remarkable transformation. With the convergence of advanced frameworks like JAX and the computational prowess of TPUs and GPUs, the barriers to entry for fine-tuning pre-trained language models have been significantly lowered. EasyDeL’s intuitive interface and powerful capabilities empower developers and researchers to unleash the full potential of LLMs, unlocking new possibilities across a myriad of domains.</p><p>Looking ahead, the journey towards mastering model adaptation promises to be one of continued innovation and discovery. As the field evolves, so too will the tools and techniques at our disposal.</p><p>In closing, let us remain vigilant in our pursuit of excellence, pushing the boundaries of what is possible and shaping a future where intelligent systems augment our capabilities and enrich our lives in ways we have yet to imagine.</p><p>This Outro is generated by the model that we have trained right now :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f38f55d3088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of LoRA: Streamlined NLP with EasyDeL in JAX]]></title>
            <link>https://medium.com/@erfanzare810/unlocking-the-power-of-lora-streamlined-nlp-with-easydel-in-jax-904896c10cb4?source=rss-ed12cdda2526------2</link>
            <guid isPermaLink="false">https://medium.com/p/904896c10cb4</guid>
            <category><![CDATA[flax]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Erfan zare Chavoshi]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 10:36:00 GMT</pubDate>
            <atom:updated>2024-02-07T10:36:00.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*WO6Wcu_xzlnS_2EUsLxKPA.png" /></figure><h3><strong>Introducing LoRA: Empowering Large Language Models with Low-Rank Adaptation</strong></h3><p>In natural language processing (NLP), the advent of Large Language Models (LLMs) has revolutionized how we interact with and analyze text data. These models, such as the GPT (Generative Pre-trained Transformer) series, have demonstrated remarkable capabilities in tasks ranging from language generation to sentiment analysis. However, the deployment of such models in real-world applications often encounters challenges related to computational resources and fine-tuning requirements.</p><p>Enter LoRA, a groundbreaking technique known as Low-Rank Adaptation, which is designed to enhance LLMs&#39; efficiency and versatility. In this article, we delve into the intricacies of LoRA and explore how it can be seamlessly integrated into your projects using EasyDeL in <strong>JAX/Flax</strong></p><h3>Understanding LoRA: The Power of Low-Rank Adaptation</h3><p>At its core, LoRA aims to mitigate the computational overhead associated with fine-tuning LLMs while preserving their performance. Traditional fine-tuning methods often demand extensive computational resources and data, making them impractical for many applications, especially those with limited resources.</p><p>LoRA takes a different approach by leveraging low-rank approximations to adapt the pre-trained LLMs to specific tasks. By identifying and preserving the most critical parameters while reducing the model’s complexity, LoRA balances computational efficiency and performance. This novel approach not only accelerates inference but also facilitates the deployment of LLMs in resource-constrained environments.</p><h4>Key Benefits of LoRA</h4><ol><li><strong>Efficiency</strong>: LoRA significantly reduces the computational overhead of fine-tuning LLMs, making them more accessible for a wide range of applications.</li></ol><p>2. <strong>Versatility</strong>: By preserving the model’s performance while reducing complexity, LoRA enables seamless integration into diverse NLP tasks without sacrificing quality.</p><p>3. <strong>Scalability</strong>: The lightweight nature of LoRA-adapted models facilitates deployment across various platforms and environments, from edge devices to cloud servers.</p><p>4. <strong>Cost-Effectiveness</strong>: With reduced computational requirements, LoRA lowers the operational costs associated with deploying and maintaining LLMs in production settings.</p><h3>Integrating LoRA into Your Projects with EasyDeL</h3><h4><strong>Let’s start with Installing Dependencies</strong></h4><pre>pip install fjformer datasets gradio wandb -U -q<br>pip install jax[tpu]==0.4.23 -f https://storage.googleapis.com/jax-releases/libtpu_releases.html -q<br>pip install tensorflow --upgrade -q<br>apt-get update &amp;&amp; apt-get upgrade -y -q &amp;&amp; apt-get install golang -y -q</pre><blockquote><em>Login With Your WANDB and HuggingFace Account too</em></blockquote><pre>python -c &quot;from huggingface_hub.hf_api import HfFolder; HfFolder.save_token(&#39;HUGGINGFACE_TOKEN&#39;)&quot;<br>wandb login WANDB_TOKEN</pre><p>Installing <a href="https://github.com/erfanzar/EasyDeL"><strong>EasyDeL</strong></a> is the core for Models and Trainers in JAX which currently supports more than 15 popular models in JAX like (MPT, Llama, Falcon, Mixtral, Qwen 1, Qwen 2, …) <a href="https://erfanzar.github.io/EasyDeL/AvailableModels/">List Available Models</a></p><p>via PyPI</p><pre>pip install easydel</pre><p>via Github (Recommended cause the latest changes are always applied)</p><pre>pip install git+https://github.com/erfanzar/EasyDeL</pre><h3>Let’s Start coding and importing packages</h3><pre>from EasyDel import (<br>    AutoEasyDelModelForCausalLM,<br>    AutoEasyDelConfig,<br>    TrainArguments, <br>    CausalLanguageModelTrainer,<br>    EasyDelOptimizers,<br>    EasyDelSchedulers,<br>    EasyDelGradientCheckPointers,<br>    EasyDelState,<br>    EasyDeLXRapTureConfig,<br>    get_modules_by_type<br>)<br>import EasyDel as ed<br>from EasyDel.etils import get_optimizer_and_scheduler<br>from datasets import load_dataset<br>from huggingface_hub import HfApi ,hf_hub_download<br>from flax.core import unfreeze, FrozenDict<br>from transformers import AutoTokenizer<br>from jax import numpy as jnp<br>from flax.traverse_util import flatten_dict,unflatten_dict<br>import jax<br>from fjformer import GenerateRNG, save_ckpt, get_dtype, CheckpointManager<br>import fjformer<br>rng_g = GenerateRNG()<br>api = HfApi()</pre><p>Now we just give the <strong><em>AutoEasyDelModelForCausalLM Module </em></strong>our targeted model repo id for example let&#39;s use Qwen1.5 or 2 which is the latest published model but feel free to use any model that you want to use.</p><pre>huggingface_path_or_repo_id = &quot;Qwen/Qwen1.5-4B&quot;<br><br><br>model, params = AutoEasyDelModelForCausalLM.from_pretrained(<br>    pretrained_model_name_or_path,<br>    device=jax.devices(&#39;cpu&#39;)[0],<br>    input_shape=(8,1),<br>    device_map=&quot;auto&quot;<br>)<br><br>config = model.config<br><br>model_parameters = FrozenDict({&quot;params&quot; : params})<br><br>dtype = jnp.bfloat16<br><br>tokenizer = AutoTokenizer.from_pretrained(<br>    huggingface_path_or_repo_id,<br>    trust_remote_code=True<br>)<br><br># This Part of the code is only being used for model performance Boost<br>## ============= ##<br>original_max_position_embedding = config.max_position_embeddings<br>config.freq_max_position_embeddings = config.max_position_embeddings<br>config.max_position_embeddings =  2048<br>config.c_max_position_embeddings = config.max_position_embeddings<br>config.use_pjit_attention_force = False<br>config.use_flash_attention = False<br>## ============= ##<br><br><br># Apply the flash attention to model [OPTIONAL]<br>## ============= ##<br>config.add_basic_configurations(<br>    attn_mechanism=&quot;flash&quot;,<br>    block_b=1,<br>    block_q=512,<br>    block_k=512,<br>    block_k_major=512,<br>)<br>## ============= ##<br><br>max_length = config.max_position_embeddings<br><br>configs_to_init_model_class={<br>    &quot;config&quot;:config,<br>    &quot;dtype&quot;: dtype,<br>    &quot;param_dtype&quot;: dtype,<br>    &quot;input_shape&quot;:(8,8)<br>}<br><br>if tokenizer.pad_token == None:<br>    tokenizer.pad_token = tokenizer.eos_token</pre><p>Now we have the model and Parameters Loaded and we can do whatever we want but let&#39;s stick to the plan load the Data and Train the Model</p><p>for now, we will use the LinguaMatic Dataset and tokenize that but you can use any other dataset that you want</p><h4><strong>EasyDeLXRapTure</strong></h4><p>what EasyDeLXRapTure is?</p><p>if I want to explain this to you I would simply say this is the module you have to use for transfer learning or LoRA in EasyDeL which takes some initial parameters and applies the configurations to them</p><p>let&#39;s jump straight into the code</p><pre>rapture_config = EasyDeLXRapTureConfig(<br>    model_parameters, # in case of using EasyDeLXRapTureConfig you have to<br>    # Pass the model parameters to Config<br>    lora_dim=64,<br>    fully_fine_tune_parameters=[&quot;embed_tokens&quot;], <br>    lora_fine_tune_parameters=[&quot;q_proj&quot;, &quot;v_proj&quot;, &quot;k_proj&quot;, &quot;o_proj&quot;],<br>    verbose=True<br>) </pre><p>for now, we will use the LinguaMatic Dataset and tokenize that but you can use any other dataset that you want</p><pre>dataset = load_dataset(&quot;erfanzar/LinguaMatic-Mixin&quot;, split=&quot;train&quot;)<br>tokenization_process = lambda data_chunk : tokenizer(data_chunk[&quot;prompt&quot;], add_special_tokens=False, max_length=max_length, padding=&quot;max_length&quot;)<br>dataset = dataset.map(<br>  tokenization_process, <br>  num_proc=12,<br>  remove_columns=dataset.column_names<br>)</pre><p>now we have to specify our training arguments I’ll use these training arguments but you can make your own and if you wonder about other wonderful options you can read Docs <a href="https://erfanzar.github.io/EasyDeL">Here</a></p><pre>train_args = TrainArguments(<br>    model_class=get_modules_by_type(config.model_type)[1],<br>    configs_to_initialize_model_class=configs_to_initialize_model_class,<br>    custom_rule=config.get_partition_rules(False),<br>    model_name=&quot;QwenLoRA&quot;,<br>    num_train_epochs=4,<br>    learning_rate=2e-4,<br>    learning_rate_end=6e-5,<br>    warmup_steps=200,<br>    optimizer=EasyDelOptimizers.ADAMW,<br>    scheduler=EasyDelSchedulers.LINEAR,<br>    weight_decay=0.02,<br>    total_batch_size=160,<br>    max_sequence_length=max_length, <br>    gradient_checkpointing=EasyDelGradientCheckPointers.NOTHING_SAVEABLE,<br>    sharding_array=(1, -1, 1, 1),<br>    use_pjit_attention_force=False,<br>    gradient_accumulation_steps=1,<br>    init_input_shape=(8,config.block_q),<br>    dtype=dtype,<br>    param_dtype=dtype,<br>    step_start_point=0, # step_start_point<br>    training_time=&quot;7H&quot;, # Maximum Training time<br>    rapture_config=rapture_config,<br>)</pre><h3>now that we have created our Training Arguments let’s train our Model</h3><pre>trainer = CausalLanguageModelTrainer(<br>    train_args,<br>    dataset.shuffle().shuffle().shuffle(),<br>    checkpoint_path=None<br>)<br><br>output = trainer.train(<br>    model_parameters=None, # You have to pass model parameters None here<br>    # cause you have passed them to RapTure Config already.<br>    state=None<br>)</pre><p>you will get live output and training config/matrics with <strong>WANDB</strong> during your training process</p><h3>Saving Model Or Converting That back to hugging face Pytorch</h3><p>here’s how you can convert your model back to Pytorch or save your easy Model</p><pre>config.max_position_embeddings = original_max_position_embeddings<br><br>new_repo_id = &quot;RPOID/MODEL_NAME&quot;<br><br>model = llama_easydel_to_hf(output.checkpoint_path, config=config).half()<br>model.push_to_hub(new_repo_id, private=False) # I Hope You love open-source too :)<br>api.upload_file(<br>    path_or_fileobj=output.checkpoint_path,<br>    repo_id=new_repo_id,<br>    path_in_repo=output.file_name<br>)</pre><h3>Conclusion</h3><p>In conclusion, with the introduction of <strong>LoRA</strong> and its seamless integration into the <strong><em>JAX</em></strong> ecosystem through <strong>EasyDeL</strong>, the landscape of natural language processing has undergone a significant transformation. LoRA’s ability to enhance the efficiency and versatility of Large Language Models, coupled with the simplicity and accessibility provided by <strong>EasyDeL</strong> in <strong><em>JAX</em></strong>, opens up new avenues for developers and researchers alike. By empowering users to effortlessly leverage the power of LoRA-adapted models in their projects, we are poised to witness accelerated innovation and breakthroughs in <strong>NLP</strong> applications. As we continue to explore and refine the capabilities of <strong>LoRA</strong> with <strong>EasyDeL</strong> in <strong>JAX</strong>, the future holds promise for even greater advancements in language understanding and generation. Join us on this journey as we pave the way toward a more efficient, scalable, and inclusive era of natural language processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=904896c10cb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Direct Preference Optimization (DPO): A User-Centric Approach to AI and Machine Learning]]></title>
            <link>https://medium.com/@erfanzare810/direct-preference-optimization-dpo-a-user-centric-approach-to-ai-and-machine-learning-d0f4796e0280?source=rss-ed12cdda2526------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0f4796e0280</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[rlhf]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Erfan zare Chavoshi]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 11:48:24 GMT</pubDate>
            <atom:updated>2024-01-12T11:48:24.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A Falcon and a llama studying together" src="https://cdn-images-1.medium.com/max/1024/1*Q19dd5RtvahKOWLYP4JGJA.png" /></figure><p>Greetings and welcome to my blog! Today, I am excited to present a detailed exploration of DPO works and what DPO is. Let’s delve into these intriguing topics, shall we?</p><p>here’s how the article sections will look like.</p><h4>1. Introduction</h4><ul><li>Briefly introduce the concept of DPO and its significance in the field of AI and machine learning.</li><li>Highlight the growing importance of user-centric approaches in technology.</li></ul><h4>2. Understanding DPO</h4><ul><li>Define DPO and explain its fundamental principles.</li><li>Discuss how DPO differs from traditional optimization methods and its potential benefits.</li></ul><h4>3. Importance of User Preferences</h4><ul><li>Explore the significance of understanding and incorporating user preferences in AI systems.</li><li>Provide examples of how user preferences impact the performance and usability of AI applications.</li></ul><h4>4. Applications of DPO</h4><ul><li>Highlight real-world applications and use cases where DPO has been successfully implemented.</li><li>Discuss how DPO can enhance personalization in recommendation systems, user interfaces, and other AI-driven technologies.</li></ul><h4>5. Challenges and Considerations</h4><ul><li>Address potential challenges and limitations associated with implementing DPO.</li><li>Discuss ethical considerations and potential biases in optimizing for user preferences.</li></ul><h4>6. Future Implications</h4><ul><li>Explore the potential impact of DPO on the future of AI and machine learning.</li><li>Discuss how DPO may contribute to more user-friendly and personalized technology experiences.</li></ul><h4>7. Conclusion</h4><ul><li>Summarize the key takeaways about DPO and its role in shaping the future of AI.</li><li>Encourage further exploration and discussion on the topic.</li></ul><h3>Introduction</h3><p>In recent years, the field of artificial intelligence (<strong><em>AI</em></strong>) and machine learning has witnessed a paradigm shift towards user-centric approaches, with Direct Preference Optimization (<strong><em>DPO</em></strong>) emerging as a pivotal concept in this evolution. <strong><em>DPO </em></strong>represents a fundamental departure from traditional optimization methods, placing a strong emphasis on directly optimizing for user preferences rather than relying on proxy objectives. This user-centric approach has garnered significant attention for its potential to revolutionize the way AI systems interact with and serve their users.</p><p>The growing importance of user-centric approaches in technology reflects a broader recognition of the pivotal role that user preferences play in shaping the effectiveness and usability of AI-driven applications. As technology becomes increasingly integrated into various aspects of our lives, the need to tailor AI systems to individual user preferences has become more pronounced. <em>DPO </em>stands at the forefront of this movement, offering a promising avenue for creating more personalized and user-centric AI experiences.</p><h3>Understanding DPO</h3><blockquote>Direct Preference Optimization (DPO) represents a novel approach in the realm of AI and machine learning, characterized by its focus on directly optimizing for user preferences. At its core, DPO seeks to tailor the behavior of AI systems to align with the specific preferences of individual users, thereby enhancing the overall user experience.</blockquote><p>Fundamentally, DPO operates on the principle of directly modeling and optimizing for user preferences, rather than relying on indirect or proxy objectives. By doing so, DPO aims to bridge the gap between user intent and system behavior, leading to more intuitive and personalized interactions.</p><p>In contrast to traditional optimization methods that often optimize for generic objectives or metrics, such as accuracy or efficiency, DPO places the user’s preferences at the forefront of the optimization process. This shift in focus holds the potential to yield more user-centric AI systems that are better equipped to understand and cater to the diverse preferences of their users.</p><p>The benefits of DPO are multifaceted. By directly optimizing for user preferences, AI systems can deliver more personalized recommendations, user interfaces, and experiences. This can lead to increased user satisfaction, improved engagement, and ultimately, more effective and impactful AI applications. Furthermore, DPO has the potential to foster greater trust and transparency in AI systems by aligning their behavior with user preferences, thereby enhancing the overall user experience.</p><h3>Importance of User Preferences</h3><blockquote>Understanding and incorporating user preferences in AI systems holds significant importance in shaping the effectiveness and user experience of AI-driven applications. By acknowledging and adapting to user preferences, AI systems can better align with the diverse needs and expectations of their users, ultimately leading to more impactful and user-centric interactions.</blockquote><p>User preferences play a pivotal role in shaping the performance and usability of AI applications across various domains. For instance, in recommendation systems, understanding user preferences is crucial for delivering personalized and relevant recommendations. By considering factors such as past behavior, explicit feedback, and contextual information, AI systems can tailor recommendations to align with individual user preferences, thereby enhancing user satisfaction and engagement.</p><p>In user interfaces and interaction design, acknowledging user preferences can significantly impact the usability and accessibility of AI applications. By accounting for factors such as language preferences, accessibility needs, and interaction styles, AI systems can create more intuitive and inclusive user experiences. This can lead to improved user adoption, satisfaction, and overall usability of the application.</p><p>Moreover, in domains such as natural language processing and conversational AI, understanding user preferences in communication styles, tone, and language nuances can greatly enhance the effectiveness of AI-driven interactions. By adapting to individual user preferences, AI systems can foster more natural and engaging conversations, leading to more meaningful and effective communication.</p><p>Overall, the significance of understanding and incorporating user preferences in AI systems lies in its potential to create more personalized, engaging, and effective user experiences across a wide range of applications and domains. By prioritizing user preferences, AI systems can better serve the diverse needs and expectations of their users, ultimately leading to more impactful and user-centric interactions.</p><h3>Applications of DPO</h3><blockquote>DPO has found compelling applications and use cases across various domains, demonstrating its potential to enhance personalization and user-centric experiences in AI-driven technologies. By directly optimizing for user preferences, DPO has been successfully implemented in real-world scenarios, revolutionizing recommendation systems, user interfaces, and other AI-driven technologies.</blockquote><p>In recommendation systems, DPO has been instrumental in delivering highly personalized and relevant recommendations to users. By directly optimizing for user preferences, DPO enables recommendation systems to consider individual user tastes, preferences, and contextual information, leading to more accurate and tailored recommendations. This personalized approach has been particularly impactful in e-commerce, content streaming platforms, and personalized marketing, where understanding and adapting to user preferences are critical for driving user engagement and satisfaction.</p><p>Moreover, in user interfaces and interaction design, DPO has been leveraged to create more intuitive and personalized experiences. By directly optimizing for user preferences in interface design, AI systems can adapt to individual user interaction styles, accessibility needs, and language preferences, leading to more inclusive and user-friendly interfaces. This personalized approach has been pivotal in enhancing the usability and accessibility of AI-driven applications across diverse user demographics and preferences.</p><p>Beyond recommendation systems and user interfaces, DPO has also demonstrated its potential to enhance personalization in conversational AI, content curation, and adaptive learning systems. By directly optimizing for user preferences, AI-driven technologies can tailor their behavior and content delivery to align with individual user preferences, fostering more engaging, relevant, and impactful user experiences.</p><p>Overall, the successful implementation of DPO in real-world applications underscores its potential to revolutionize personalization and user-centric experiences in AI-driven technologies. By directly optimizing for user preferences, DPO has paved the way for more tailored, engaging, and effective interactions across a wide spectrum of applications and domains, ultimately shaping the future of user-centric AI experiences.</p><h3>Challenges and Considerations</h3><p>While Direct Preference Optimization (DPO) holds promise in revolutionizing user-centric AI experiences, its implementation is not without challenges and considerations. Addressing these potential hurdles is crucial for realizing the full potential of DPO and ensuring its ethical and effective application in AI and machine learning.</p><p>One significant challenge associated with implementing DPO lies in the accurate and comprehensive understanding of user preferences. User preferences are multifaceted and dynamic, encompassing a wide range of individual tastes, needs, and contextual factors. Effectively capturing and interpreting these preferences to inform the optimization process can be complex, requiring robust data collection, user feedback mechanisms, and sophisticated modeling techniques.</p><p>Furthermore, ethical considerations and potential biases in optimizing for user preferences represent critical considerations in the implementation of DPO. Optimizing solely for user preferences may inadvertently reinforce existing biases or inadvertently lead to filter bubbles, where users are only exposed to information or content that aligns with their existing preferences, potentially limiting their exposure to diverse perspectives. Additionally, there is a risk of inadvertently amplifying certain preferences over others, potentially leading to a lack of diversity in the content or recommendations presented to users.</p><p>Moreover, ensuring transparency, user control, and the ethical use of personal data in the context of DPO is paramount. Respecting user privacy, providing clear mechanisms for user feedback and control, and mitigating the potential for unintended consequences are essential considerations in the ethical implementation of DPO.</p><p>Addressing these challenges and considerations requires a holistic approach that integrates robust data governance, transparency, user empowerment, and ongoing ethical scrutiny. By proactively addressing these challenges, the implementation of DPO can be guided by ethical principles, ensuring that user preferences are optimized for in a responsible, inclusive, and transparent manner.</p><h3>Future Implications</h3><p>The emergence of Direct Preference Optimization (DPO) holds profound implications for the future of AI and machine learning, offering the potential to reshape the landscape of user-friendly and personalized technology experiences. As DPO continues to evolve and gain traction, its impact is poised to extend across various domains, fundamentally altering the way AI systems interact with and serve their users.</p><p>DPO’s emphasis on directly optimizing for user preferences heralds a future where AI-driven technologies can deliver more tailored, intuitive, and user-centric experiences. By prioritizing user preferences in the optimization process, DPO has the potential to foster a new era of personalization, where AI systems can adapt to individual user needs, tastes, and contextual factors, leading to more engaging and impactful interactions.</p><p>In the realm of recommendation systems and content delivery, the integration of DPO may lead to a paradigm shift, where users are presented with highly personalized and relevant recommendations that align closely with their individual preferences. This personalized approach has the potential to enhance user satisfaction, drive user engagement, and foster a deeper sense of connection with AI-driven content and services.</p><p>Moreover, in user interfaces and interaction design, the application of DPO may pave the way for more inclusive, accessible, and user-friendly experiences. By tailoring interface design and interaction styles to align with individual user preferences, AI systems can create more intuitive and adaptive interfaces, accommodating diverse user needs and preferences.</p><p>Furthermore, the future implications of DPO extend to conversational AI, adaptive learning systems, and beyond, where the direct optimization for user preferences may lead to more natural, relevant, and impactful user experiences.</p><p>Overall, the potential impact of DPO on the future of AI and machine learning is profound, offering the promise of more user-friendly, personalized, and impactful technology experiences. By prioritizing user preferences in the optimization process, DPO has the potential to usher in a new era of AI-driven interactions, where user needs and preferences are at the forefront, ultimately shaping the future of user-centric AI experiences.</p><h3>Conclusion</h3><blockquote>Direct Preference Optimization (DPO) stands at the forefront of a transformative shift in the realm of AI and machine learning, emphasizing the direct optimization for user preferences to shape more personalized and user-centric technology experiences. As we reflect on the significance of DPO and its role in shaping the future of AI, several key takeaways emerge.</blockquote><p>DPO represents a fundamental departure from traditional optimization methods, placing a strong emphasis on directly optimizing for user preferences rather than relying on proxy objectives. This user-centric approach has the potential to revolutionize the way AI systems interact with and serve their users, fostering more tailored, intuitive, and impactful experiences.</p><p>The successful implementation of DPO in real-world applications, such as recommendation systems, user interfaces, and conversational AI, underscores its potential to enhance personalization and user-centric experiences across diverse domains. By directly optimizing for user preferences, DPO has paved the way for more tailored, engaging, and effective interactions, ultimately shaping the future of user-centric AI experiences.</p><p>As we look ahead, it is essential to encourage further exploration and discussion on the topic of DPO. The ethical considerations, potential challenges, and future implications of DPO warrant ongoing scrutiny and dialogue. By fostering a deeper understanding of DPO and its implications, we can collectively shape a future where AI-driven technologies are more user-friendly, inclusive, and impactful.</p><p>In conclusion, DPO represents a pivotal concept in the evolution of AI and machine learning, offering the promise of more personalized, user-centric, and impactful technology experiences. By prioritizing user preferences in the optimization process, DPO has the potential to shape the future of AI, ultimately fostering more tailored, intuitive, and engaging interactions. It is imperative to continue exploring and discussing the implications of DPO, ensuring that its implementation is guided by ethical principles and a commitment to user-centric experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0f4796e0280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring LLM Training and Hosting with JAX and EasyDel]]></title>
            <link>https://medium.com/@erfanzare810/exploring-llm-training-and-hosting-with-jax-and-easydel-2db59af1442f?source=rss-ed12cdda2526------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db59af1442f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Erfan zare Chavoshi]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 11:03:24 GMT</pubDate>
            <atom:updated>2024-01-06T11:03:24.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*AyFJT3wvc5dcsawgioasQw.jpeg" /></figure><p>Greetings and welcome to my blog! Today, I am excited to present a detailed exploration of how you can train and host LLMs, using the powerful JAX library and EasyDel. Let’s delve into these intriguing topics, shall we?</p><ol><li><strong>How To Train Your LLM Llama</strong></li><li>How To Train Your LLM Mistral, Mixtral, or any other LLM</li><li>How To Host Your LLM</li></ol><p><strong><em>To illustrate the process of training your own Llama, we’ll utilize the power of TPUs. Specifically, we’ll directly access the Kaggle TPU VM 3–8 to harness the exceptional computational capabilities of these specialized devices. However, it’s worth noting that this script can be readily adapted to run on other accelerators, including GPUs or local machines. For instance, if you have a GPU, you could replace Kaggle TPU VM 3–8 with your local GPU. Likewise, if you have multiple GPUs, you could run the script on all of them simultaneously. If there’s a local machine available, you can leverage that as well. This flexibility makes the script highly adaptable, allowing you to use your preferred hardware setup.</em></strong></p><p>The revised paragraph emphasizes the flexibility of the training process, ensuring that readers understand they can utilize their preferred hardware setup. It also maintains a concise and informative tone, making it easier for readers to grasp the concepts presented.</p><p>Let’s begin with the installation process of our dependencies. How to install Dependencies: The first step involves installing ‘former’, which is essential for our EasyDel and works as a compute backend of EasyDel and carries some stuff like TPU/GPU FlashAttention, Utilities, Optimizers, Loggers, Partition Utils, etc.</p><h4>Let&#39;s start with Installing Dependencies</h4><pre>pip install fjformer datasets gradio wandb -U -q<br>pip install jax[tpu]==0.4.17 -f https://storage.googleapis.com/jax-releases/libtpu_releases.html -q<br>pip install tensorflow --upgrade -q<br>apt-get update &amp;&amp; apt-get upgrade -y -q &amp;&amp; apt-get install golang -y -q</pre><p>we use JAX version 0.4.17 to stop low bandwidth kernel crashing in Kaggle but you can use any JAX version higher than <strong><em>0.4.16</em></strong></p><blockquote>Login With Your WANDB and HuggingFace Account too</blockquote><pre>python -c &quot;from huggingface_hub.hf_api import HfFolder; HfFolder.save_token(&#39;HUGGINGFACE_TOKEN&#39;)&quot;<br>wandb login WANDB_TOKEN</pre><p>Installing <a href="https://github.com/erfanzar/EasyDeL"><strong>EasyDeL</strong></a> is the core for Models and Trainers in JAX which currently supports more than 10 popular models in JAX like (MPT, Llama, Falcon, Mixtral, …) <a href="https://erfanzar.github.io/EasyDeL/AvailableModels/">List Available Models</a></p><p>via PyPI</p><pre>pip install easydel</pre><p>via Github (Recommended cause the latest changes are always applied)</p><pre>pip install git+https://github.com/erfanzar/EasyDeL</pre><h4>Let&#39;s Start coding and importing packages</h4><pre>from EasyDel import (<br>    AutoEasyDelModelForCausalLM,<br>    TrainArguments, <br>    CausalLanguageModelTrainer,<br>    llama_easydel_to_hf,<br>    EasyDelOptimizers,<br>    EasyDelSchedulers,<br>    EasyDelGradientCheckPointers<br>)<br>import EasyDel as ed<br>from datasets import load_dataset<br>from huggingface_hub import HfApi ,hf_hub_download<br>from flax.core import unfreeze, FrozenDict<br>from transformers import AutoTokenizer<br>from jax import numpy as jnp<br>from flax.traverse_util import flatten_dict,unflatten_dict<br>import jax<br>from fjformer import GenerateRNG, save_ckpt ,get_float_dtype_by_name<br><br>rng_g = GenerateRNG()<br>api = HfApi()</pre><p>we can train models up to 10B with context length 2K even on Free Kaggle TPUs (128GB VRAM or RAM) thanks to JAX and some other lower-level processes but for the start let&#39;s load a <strong>TinyLlama-1.1B </strong>but remember you can you any other model architecture and other models as you want</p><pre>huggingface_path_or_repo_id = &quot;TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T&quot;<br><br><br>model, params = AutoEasyDelModelForCausalLM.from_pretrained(<br>    huggingface_path_or_repo_id,<br>    device=jax.devices(&quot;cpu&quot;)[0],<br>    input_shape=(8,1),<br>    device_map=&quot;auto&quot;<br>)<br><br>tokenizer = AutoTokenizer.from_pretrained(<br>    huggingface_path_or_repo_id,<br>    trust_remote_code=True<br>)<br><br><br>config = model.config<br><br># This Part of the code is only being used for model performance Boost<br>## ============= ##<br>original_max_position_embedding = config.max_position_embeddings<br>config.freq_max_position_embeddings = config.max_position_embeddings<br>config.max_position_embeddings =  2048<br>config.c_max_position_embeddings = config.max_position_embeddings<br>config.use_pjit_attention_force = False<br>config.use_flash_attention = False<br>## ============= ##<br><br>max_length = config.max_position_embeddings<br><br>configs_to_init_model_class={<br>    &quot;config&quot;:config,<br>    &quot;dtype&quot;:jnp.bfloat16,<br>    &quot;param_dtype&quot;:jnp.bfloat16,<br>    &quot;input_shape&quot;:(8,8)<br>}<br><br>if tokenizer.pad_token == None:<br>    tokenizer.pad_token = tokenizer.eos_token</pre><p>Now we have the model and Parameters Loaded and we can do whatever we want but let&#39;s stick to the plan load the Data and Train the Model</p><p>for now, we will use the LinguaMatic Dataset and tokenize that but you can use any other dataset that you want</p><pre>dataset = load_dataset(&quot;erfanzar/LinguaMatic-Mixin&quot;, split=&quot;train&quot;)<br>tokenization_process = lambda data_chunk : tokenizer(data_chunk[&quot;prompt&quot;], add_special_tokens=False, max_length=max_length, padding=&quot;max_length&quot;)<br>dataset = dataset.map(<br>  tokenization_process, <br>  num_proc=12,<br>  remove_columns=dataset.column_names<br>)</pre><p>now we have to specify our training arguments I&#39;ll use these training arguments but you can make your own and if you wonder about other wonderful options you can read Docs <a href="https://erfanzar.github.io/EasyDeL">Here</a></p><pre>train_args = TrainArguments(<br>    model_class=type(model),<br>    configs_to_init_model_class=configs_to_init_model_class,<br>    custom_rule=config.get_partition_rules(True),<br>    model_name=&quot;MyFirstModelWith-EasyDel&quot;,<br>    num_train_epochs=3,<br>    learning_rate=8e-5,<br>    learning_rate_end=4e-05,<br>    warmup_steps=200,<br>    optimizer=EasyDelOptimizers.ADAMW,<br>    scheduler=EasyDelSchedulers.COSINE,<br>    weight_decay=0.02,<br>    total_batch_size=28,<br>    max_length=max_length, <br>    gradient_checkpointing=EasyDelGradientCheckPointers.NOTHING_SAVEABLE,<br>    sharding_array=(1, -1, 1, 1),<br>    use_pjit_attention_force=False,<br>    gradient_accumulation_steps=2,<br>    dtype=jnp.bfloat16,<br>    init_input_shape=(8,8),<br>)</pre><h4>now that we have created our Training Arguments let&#39;s train our Model</h4><pre>trainer = CausalLanguageModelTrainer(<br>    train_args,<br>    dataset,<br>    checkpoint_path=None<br>)<br><br>output = trainer.train(FrozenDict({&#39;params&#39; : params}))</pre><p>you will get live output and training config/matrics with <strong>WANDB</strong> during your training process</p><h4>Saving Model Or Converting That back to hugging face Pytorch</h4><p>here’s how you can convert your model back to Pytorch or save your easy Model</p><pre>config.max_position_embeddings = original_max_position_embeddings<br><br>new_repo_id = &quot;RPOID/MODEL_NAME&quot;<br><br>model = llama_easydel_to_hf(output.checkpoint_path, config=config).half()<br>model.push_to_hub(new_repo_id, private=False) # I Hope You love open-source too :)<br>api.upload_file(<br>    path_or_fileobj=output.checkpoint_path,<br>    repo_id=new_repo_id,<br>    path_in_repo=output.file_name<br>)</pre><h4>Conclusion</h4><p>“With this, we’ve reached the conclusion of our exploration into LLM training and hosting. We hope this journey has equipped you with the knowledge and tools to effectively train and deploy LLMs using JAX and EasyDel. Remember, the possibilities are endless, and the power of LLMs is waiting to be unleashed to address diverse challenges and enhance various applications. Thank you for joining us on this insightful journey.”</p><p>The revised conclusion serves as a satisfying closure to the blog post, reiterating the key takeaways and expressing gratitude to the readers for their engagement. It also leaves a sense of optimism and encourages readers to further explore the potential of LLMs, thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db59af1442f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>