<?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 Alexander Uspenskiy on Medium]]></title>
        <description><![CDATA[Stories by Alexander Uspenskiy on Medium]]></description>
        <link>https://medium.com/@alexander-uspenskiy?source=rss-9a952b164da0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UQdCD_ZzG_utAPpm</url>
            <title>Stories by Alexander Uspenskiy on Medium</title>
            <link>https://medium.com/@alexander-uspenskiy?source=rss-9a952b164da0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:42:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexander-uspenskiy/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[Unlock DeepSeek R1 7B on Your Laptop — Experience the Smartest AI Model I Ever Tested!]]></title>
            <link>https://alexander-uspenskiy.medium.com/unlock-deepseek-r1-7b-on-your-laptop-experience-the-smartest-ai-model-i-ever-tested-72eaa3f55329?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/72eaa3f55329</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 20:31:37 GMT</pubDate>
            <atom:updated>2025-02-05T20:31:37.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlock DeepSeek R1 7B on Your Laptop — Experience the Smartest AI Model I Ever Tested!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ys-W-MqJNBy2CCpz55Tktg.jpeg" /></figure><p>To be honest, I didn’t have high expectations for the buzz surrounding DeepSeek R1. However, I decided to test the 7B DeepSeek model, deepseek-ai/deepseek-r1-distill-qwen-7b, and what I discovered truly amazed me.</p><p>So let’s start.</p><p>This is a project that utilizes transformer models for generating responses to user queries. It leverages the transformers library from HuggingFace and torch for efficient model handling and inference.</p><h3>Setup</h3><h3>Prerequisites</h3><ul><li>Python 3.7 or higher</li><li>pip (Python package installer)</li></ul><h3>Installation</h3><ol><li>Clone the repository:</li></ol><pre>git clone https://github.com/alexander-uspenskiy/deepseek <br>cd deepseek</pre><p>2. Create and activate a virtual environment:</p><pre>python -m venv venv source venv/bin/activate</pre><p>3. Install the required packages:</p><pre>pip install transformers torch</pre><h3>Usage</h3><ol><li>Run the main script:</li></ol><pre>python deepseek.py</pre><p>Follow the prompts to enter your questions. Type ‘quit’ to exit the interaction.</p><h3>Project Structure</h3><p>deepseek.py: Main script containing the model setup and response generation logic.</p><h3>Example</h3><pre>(venv) $ python deepseek.py</pre><pre>Enter your question (or &#39;quit&#39; to exit): A bat and a ball costs 1 dollar and 10 cents in total. The bat costs 1 dollar more than a ball. How much does the ball costs?</pre><pre>Response: Question: A bat and a ball costs 1 dollar and 10 cents in total. The bat costs 1 dollar more than a ball. How much does the ball costs?<br>Answer: 5 cents.</pre><pre>But wait, that doesn&#39;t make sense. If the ball is 5 cents, then the bat is 1 dollar more, which would be $1.05, and together that&#39;s $1.10. So, the ball is 5 cents.</pre><pre>Wait, but that seems a bit tricky. Let me think again. Maybe I should set up some equations to solve this properly.</pre><pre>Let me denote the cost of the ball as \( x \) dollars. Then, according to the problem, the bat costs \( x + 1 \) dollars. The total cost of the bat and the ball is $1.10, so:</pre><pre>\( x + (x + 1) = 1.10 \)</pre><pre>Simplify the equation:</pre><pre>\( 2x + 1 = 1.10 \)</pre><pre>Subtract 1 from both sides:</pre><pre>\( 2x = 0.10 \)</pre><pre>Divide both sides by 2:</pre><pre>\( x = 0.05 \)</pre><pre>So, the ball costs 5 cents. That seems correct, but let me verify.</pre><pre>If the ball is 5 cents, the bat is $1.05. Adding them together: 5 + 105 = 110 cents, which is $1.10. Yes, that checks out.</pre><pre>Wait, but sometimes these problems can be tricky. Is there any other way to interpret the problem that could lead to a different answer? Maybe the phrasing could be ambiguous. Let me read it again:</pre><pre>&quot;A bat and a ball costs 1 dollar and 10 cents in total. The bat costs 1 dollar more than a ball. How much does the ball costs?&quot;</pre><pre>Hmm, no, the way it&#39;s phrased seems pretty straightforward. It says the total is $1.10, and the bat is $1 more than the ball. So, with the equations I set up, it leads to the ball being 5 cents.</pre><p>As you see the response shows the whole reasoning process which is amazing for the model that can be executed on your laptop.</p><h3>Source Code</h3><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import torch<br>def setup_model():<br>    # Model ID from HuggingFace<br>    model_id = &quot;deepseek-ai/deepseek-r1-distill-qwen-7b&quot;<br>    # Initialize tokenizer<br>    tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)<br>    # Load model with lower precision for memory efficiency<br>    model = AutoModelForCausalLM.from_pretrained(<br>        model_id,<br>        torch_dtype=torch.float16,  # Use fp16 for efficiency<br>        device_map=&quot;auto&quot;,  # Automatically handle device placement<br>        trust_remote_code=True<br>    )<br>    return model, tokenizer<br>def generate_response(model, tokenizer, prompt, max_length=512):<br>    # Tokenize input<br>    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;, padding=True, truncation=True).to(model.device)<br>    # Generate response<br>    with torch.no_grad():<br>        outputs = model.generate(<br>            inputs.input_ids,<br>            attention_mask=inputs.attention_mask,  # Pass attention_mask<br>            max_length=max_length,<br>            temperature=0.7,<br>            top_p=0.9,<br>            do_sample=True,<br>            pad_token_id=tokenizer.pad_token_id,<br>        )<br>    # Decode and return response<br>    response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>    return response<br>def main():<br>    try:<br>        # Setup model and tokenizer<br>        model, tokenizer = setup_model()<br>        # Example QA interaction<br>        while True:<br>            question = input(&quot;\nEnter your question (or &#39;quit&#39; to exit): &quot;)<br>            if question.lower() == &#39;quit&#39;:<br>                break<br>            prompt = f&quot;Question: {question}\nAnswer:&quot;<br>            response = generate_response(model, tokenizer, prompt)<br>            print(f&quot;\nResponse: {response}&quot;)<br>    except Exception as e:<br>        print(f&quot;An error occurred: {str(e)}&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Troubleshooting</h3><p>If you encounter issues with the model download or execution, ensure that your internet connection is stable and try the following steps:</p><ol><li>Ensure the virtual environment is activated:</li></ol><pre>source venv/bin/activate</pre><p>2. Reinstall the required packages:</p><pre>pip install --upgrade transformers torch</pre><p>3. Check the Python interpreter being used:</p><pre>which python</pre><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72eaa3f55329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Fine-Tune Your Resume with These 360-Degree Free AI Tools:]]></title>
            <link>https://alexander-uspenskiy.medium.com/fine-tune-your-resume-with-these-360-degree-free-ai-tools-90fe2f2b85a8?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/90fe2f2b85a8</guid>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 18:02:40 GMT</pubDate>
            <atom:updated>2024-12-17T18:12:28.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJ08h4mUdF4TuL5L-ma2jQ.jpeg" /></figure><p>🚀 Fine-Tune Your Resume with These <strong>360-Degree Free AI Tools:</strong></p><ol><li><strong>ResumeALLY — Automated Resume Scoring for Improved Hiring</strong></li></ol><p>— Analyzes your resume and provides an Applicant Tracking System (ATS) Score<br> — Detailed instructions for optimization.</p><p><a href="https://partyrock.aws/u/Alexu/FhpEt3oEc/ResumeALLY-Automated-Resume-Scoring-for-Improved-Hiring"><strong>https://partyrock.aws/u/Alexu/FhpEt3oEc/ResumeALLY-Automated-Resume-Scoring-for-Improved-Hiring</strong></a></p><p>2. <strong>Resume-Job Fit Analyzer</strong><br> <br>— Reveals Match Score and offers guidance on resume optimization for ATS success<br>— Improves your chances of securing interview invitations</p><p><a href="https://partyrock.aws/u/Alexu/Lk2E4BrD8/Resume-Job-Fit-Analyzer"><strong>https://partyrock.aws/u/Alexu/Lk2E4BrD8/Resume-Job-Fit-Analyzer</strong></a></p><p>3. <strong>CoverAce — Your Personalized Cover Letter Generator:</strong></p><p>— Tailors cover letters for job applications<br>— Personalized approach for effective communication</p><p><a href="https://partyrock.aws/u/Alexu/KoDbaaSbG/CoverAce%3A-Your-Personalized-Cover-Letter-Generator"><strong>https://partyrock.aws/u/Alexu/KoDbaaSbG/CoverAce%3A-Your-Personalized-Cover-Letter-Generator</strong></a></p><p>Enhance your job application documents with these AI-powered tools to stand out to potential employers! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90fe2f2b85a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Immortality: Teaching AI to Be Your Future Self]]></title>
            <link>https://alexander-uspenskiy.medium.com/do-you-want-to-integrate-your-digital-identity-into-an-llm-to-preserve-your-footprint-for-the-8fe5d3451c91?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fe5d3451c91</guid>
            <category><![CDATA[digital-identity]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[digital-identity-solution]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 19:13:57 GMT</pubDate>
            <atom:updated>2024-11-17T19:28:37.093Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-U4Bp3zgD0TMszsuFrIHQ.jpeg" /><figcaption>Digital Double</figcaption></figure><blockquote>Disclaimer: The scope of this article related to implementation of possibility to build “Digital Identity”. The ethical and philosophy and social questions are a wide topics and not fall to the scope of this article</blockquote><p>Have you ever considered having a digital representation or a virtual double in the AI world?</p><p>Since AIG is not implemented yet as of November 2024 but the big LLMs like GPT 4, Claude, Gemini etc are smart enough to support a meaningful conversation is is time to think about your digital identity that can be used in several diverse, usual and a bit strange ways at the moment:</p><blockquote>1. To be your virtual representative, your day to day assistant, your second identity to help you with the day-to day routine like email conversations, scheduling, base finance management, personal adviser who knows you well enough to make a valuable advices.</blockquote><blockquote>2. Your footprint for a future generations, for example you grand-grand childs can chat with your digital identity and know more about you and keep the link between a generations.</blockquote><p>How this can be physical happen?</p><p>If we check how modern AI/ML science evolves we can have some different approaches to implementation of Digital Identity:</p><p><strong>RAG.</strong> Modern AI language models can now be augmented with specialized knowledge through a technique called <strong>RAG (Retrieval-Augmented Generation).</strong>This approach combines the model’s inherent capabilities with an external knowledge base stored in a vector database. The knowledge base contains information, actually your “personal knowledge, your “personality”, broken down into digestible chunks of text, which are converted into mathematical representations called embeddings. When the AI needs to access specific information or maintain consistent personality traits, it can retrieve and reference these relevant knowledge snippets from the database. This architecture allows the AI to draw upon a curated pool of knowledge while maintaining the fluidity and natural language understanding of large language models. Think of it as giving the AI instant access to a personal library of information about you, which it can seamlessly integrate into its responses, as example (it can be structured like “Question”, “Answer” or unstructured text like you diary, autobiography, video, audio — for Multimodal AI Models):</p><pre>{<br>  &quot;Question&quot;: &quot;What are my favorite food?&quot;,<br>  &quot;Answer&quot;: &quot; I like BBQ, Texas style steaks&quot;<br>}<br> </pre><p>Here is the very high level diagram of RAG architecture (local or Cloud based):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7ec5l0g50VQiJZ-JFEd5w.png" /><figcaption>RAG architecture</figcaption></figure><p>User creates prompt, query enriched with the relevant context from the Knowledge Base and LLM responses to the prompt using a relevant context.</p><p>Example of enriched request:</p><pre>{<br>  Answer the question: &quot;Do you like steaks?&quot; using this context: &quot;I like BBQ, Texas style steaks&quot;<br>}</pre><p><strong>Fine-tuning </strong>represents a powerful approach to customizing large language models (LLMs) for specific use cases. This process involves additional training of an existing model using your specialized dataset, essentially teaching the model to become an expert in your domain.</p><p>Key Advantages:</p><ul><li>Streamlined Architecture: Unlike RAG systems, fine-tuned models don’t require external knowledge bases or vector databases, as the domain knowledge becomes integrated into the model’s parameters</li><li>Enhanced Performance: When trained on high-quality, domain-specific data, these models can deliver more accurate and contextually appropriate responses</li><li>Faster Inference: Without the need to query external databases, fine-tuned models can potentially offer quicker response times</li></ul><p>Technical Challenges: The fine-tuning process, while powerful, comes with significant technical demands:</p><ul><li>Substantial Computing Resources: Training modern LLMs requires access to high-performance hardware, including specialized GPUs and large amounts of memory</li><li>Storage Infrastructure: Managing the training process necessitates robust storage systems to handle massive datasets</li><li>Technical Expertise: Success depends heavily on machine learning expertise, including understanding of model architecture, training dynamics, and optimization techniques</li><li>Cost Considerations: The computational intensity of fine-tuning can translate into significant infrastructure and operational expenses</li></ul><p>While fine-tuning offers a path to superior performance for specific applications, organizations must carefully weigh these technical requirements against their available resources and expertise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xljq4T_YXuNR7_6VxLrFNQ.png" /><figcaption>Fine Tuning</figcaption></figure><p>Using this approach we train already pre-trained model using dataset with personal details, so we’re not train brand new model from a scratch but just adding “personality” to the model.</p><h3><strong>Preparing Dataset</strong></h3><p>One of the main question is the requirements to the dataset to be able to train the model to receive an adequate result.</p><p>Let’s try to see what options do we have and which techniques can we use.</p><p>Explicit Consent &amp; Data Collection:</p><ul><li>Ask user to voluntarily share their preferences and information</li><li>Use transparent surveys and questionnaires</li><li>Allow users to review and control what data is stored</li></ul><p>Classification of data to be collected</p><ol><li>Professional Identity:</li></ol><ul><li>Career background and expertise areas</li><li>Industry specializations</li><li>Professional goals and aspirations</li><li>Preferred communication style in work context</li><li>Common work-related tasks and challenges</li></ul><p>2. Personal Identity:</p><ul><li>Family details</li><li>Personal Preferences (food, sport, hobbies etc)</li><li>Behavioral Preferences (party, travels etc…)</li><li>History details</li><li>etc</li></ul><p>3. Learning &amp; Problem-Solving:</p><ul><li>Preferred learning style (visual, text, interactive)</li><li>Knowledge areas of interest</li><li>Decision-making approach</li><li>Problem-solving methodology preferences</li><li>Information processing style (detail vs big picture)</li></ul><p>4. Communication Preferences:</p><ul><li>Preferred level of formality</li><li>Response length preferences (concise vs detailed)</li><li>Preferred explanation style (examples, analogies, step-by-step)</li><li>Language preferences</li><li>Feedback style preferences</li></ul><p>5. Digital Interaction Style:</p><ul><li>Preferred content formats</li><li>Task organization methods</li><li>Technology comfort level</li><li>Tool preferences</li><li>Response time expectations</li></ul><p>6. Personal Development Goals:</p><ul><li>Skills wanting to develop</li><li>Topics interested in learning</li><li>Personal growth objectives</li><li>Productivity preferences</li><li>Time management style</li></ul><p>Best Practices to collect personal dataset:</p><ul><li>Make all questions optional</li><li>Explain how data will be used</li><li>Allow users to update preferences</li><li>Provide clear privacy policies</li><li>Include data deletion options</li><li>Start with essential questions and allow progressive profiling</li></ul><blockquote>Security warning: Since you’re collecting private information you should be extra careful with data protection, newer share dataset, Knowledge Base, Fine Tuned Models with non-trusted 3rd party, encrypt data in rest and data-in-transfer with a strong cryptography ( like AES, RSA, SSL/TLS/HTTPS)</blockquote><h3>Why I can’t train the LLM model just using prompt?</h3><p>At the moment the main problem of a modern LLM models is a short context window, let’s compare the most advanced models:</p><ul><li>Claude 3 Opus: 200K tokens</li><li>Claude 3 Sonnet: 200K tokens</li><li>Anthropic Claude 2.1: 200K tokens</li><li>Google Gemini Ultra: 128K tokens</li><li>GPT-4 Turbo: 128K tokens</li><li>Mistral Large: 128K tokens</li></ul><p>Let‘s’ break down the approximate text capacity of 200K tokens in English:</p><p>General Approximations for 200K tokens:</p><ul><li>Words: ~150,000 words (as tokens to words ratio is roughly 4:3 in English)</li></ul><p>This translates to approximately:</p><ul><li>300–400 pages of a typical book</li><li>500–600 pages of regular typed text</li><li>A small novel</li><li>~150 academic papers (1000 words each)</li><li>~100 detailed blog posts</li></ul><p>Common Document Equivalents:</p><ul><li>50–75 research papers with references</li><li>3–4 PhD theses</li><li>Several technical documentation manuals</li></ul><p>Practical Examples:</p><ul><li>The complete Shakespeare play “Hamlet” (~30K words)</li><li>First two Harry Potter books combined</li></ul><p>It seems not so bad, but on practice chatbots like Chat GPT sends all the chat context which every prompt so it is really memory consuming operation so context window over very fast and you have to start a new chat and lost the chat history so at least with the current state of LLM the context is still pretty small for a detailed Personal Identity Profile.</p><p>Let me explain why even a large 200K token context window can fill up quickly during chat interactions:</p><p>Complete Conversation Storage:</p><ul><li>Each message includes metadata and formatting</li><li>Both user and assistant messages are stored</li><li>Timestamps and session information</li><li>System prompts and instructions</li><li>Model’s personality and behavior guidelines</li><li>Previous context and referenced information</li></ul><p>Assistant’s Internal Processing:</p><ul><li>Detailed reasoning steps (even if not shown)</li><li>Multiple iterations of thought processes</li><li>Analysis of previous context</li><li>Maintaining consistency with past responses</li><li>Tracking conversation thread and topics</li></ul><p>Real-world Chat Volume Example:</p><pre>Per typical conversation turn:<br>- User message: 50-100 tokens<br>- Assistant thinking: 100-200 tokens<br>- Assistant response: 200-500 tokens<br>- Metadata/formatting: 50-100 tokens<br>Total per turn: ~400-900 tokens</pre><pre>In active usage:<br>- 30 conversation turns per hour<br>- 8 hours of active chat<br>- ~(400-900) × 30 × 8 = 96,000-216,000 tokens</pre><p>Additional Overhead:</p><ul><li>Quoted text and references</li><li>Examples and explanations</li><li>Lists and structured data</li><li>Embedded instructions and guidelines</li></ul><p>This shows how even a “day’s worth” of meaningful conversation can easily exceed 200K tokens, especially in professional or technical discussions where context preservation is crucial.</p><h3>Summary</h3><p>As of today, it is technically possible to create a functional representation of your Digital Identity or a digital twin (via Knowledge Base or fine-tuned LLM model as shown in the article). However, your digital counterpart wouldn’t possess the ability to think in the way we understand the process or make groundbreaking innovations. Still, this marks a significant first step toward what we might call a “digital super-you” or “your AI-generated self (AIG).”</p><p>The primary challenges are clear:</p><ul><li>Developing a powerful and intelligent large language model (LLM or AIG).</li><li>Gathering a comprehensive and complete dataset that encapsulates a 360-degree view of your personality.</li></ul><p>Let’s briefly delve into the challenges surrounding the dataset:</p><h3><strong>1. Complexity of Personality</strong></h3><ul><li><strong>Human personality</strong> is dynamic and multifaceted, influenced by genetics, environment, experiences, emotions, and social contexts.</li><li>Capturing all aspects of personality would require data about every thought, emotion, decision, and behavior, as well as their underlying causes, which is both technically and ethically unfeasible.</li></ul><h3>2. Limitations of Data Collection</h3><ul><li><strong>Data diversity</strong>: Human behavior changes across different situations, times, and cultures. No dataset can comprehensively account for all contexts.</li><li><strong>Measurement challenges</strong>: While tools like psychometric tests, social media behavior analysis, and biometrics can provide insights, they are incomplete and may introduce biases or inaccuracies.</li><li><strong>Privacy concerns</strong>: Collecting deeply personal data raises significant ethical and legal issues, such as consent, misuse, and potential harm.</li></ul><h3>3. Neuroscience and Technology Gaps</h3><ul><li>The brain is still not fully understood. Although technologies like fMRI, EEG, and brain-computer interfaces provide insights into neural activity, they can’t fully decode thoughts or emotions.</li><li>AI models can simulate personality traits or behaviors based on available data, but they lack the subjective experiences and consciousness of a human being.</li></ul><h3>4. Ethical Considerations</h3><ul><li>Collecting a “complete dataset” would involve intrusive monitoring, violating fundamental rights to privacy and autonomy.</li><li>Representation of such data risks misuse, such as manipulation or exploitation, leading to ethical dilemmas.</li></ul><h3>Current Approximations</h3><p>While a true 360-degree dataset is unattainable, <strong>partial representations</strong> can be built using:</p><ul><li><strong>Psychometric assessments</strong>: Tools like the Big Five Personality Test or MBTI.</li><li><strong>Digital footprints</strong>: Social media activity, browsing history, or purchasing patterns.</li><li><strong>AI models</strong>: Simulations based on observed behaviors or input data (e.g., chatbots mimicking communication styles).</li></ul><blockquote>The emergence of highly personalized artificial intelligence, or ‘digital twins,’ appears to be an imminent reality rather than a distant possibility. As these AI counterparts become more sophisticated and prevalent, society faces a crucial challenge: establishing frameworks for meaningful and secure interactions between humans and their digital alter egos.</blockquote><p>This technological evolution will require humanity to develop new paradigms for:</p><ul><li>Understanding the boundaries between human and artificial intelligence</li><li>Creating safe and ethical guidelines for human-AI relationships</li><li>Maintaining privacy and security in an interconnected world</li><li>Balancing the benefits of personalized AI with potential risks</li><li>Building trust while preserving human autonomy</li></ul><p>As we stand on the threshold of this transformation, proactively addressing these considerations becomes essential for ensuring a harmonious integration of digital twins into our daily lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fe5d3451c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Your Own RAG with Free LLM Models and a Knowledge Base]]></title>
            <link>https://alexander-uspenskiy.medium.com/how-to-create-your-own-rag-with-free-llm-models-and-a-knowledge-base-cea9185ff96d?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea9185ff96d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 18:09:42 GMT</pubDate>
            <atom:updated>2024-11-10T18:24:56.215Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>This article explores the implementation of a straightforward yet effective question-answering system that combines modern transformer-based models. The system uses T5 (Text-to-Text Transfer Transformer) for answer generation and Sentence Transformers for semantic similarity matching.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBZyhK4DW6cCEgOc2llnXA.jpeg" /><figcaption>How to write your own RAG with a Free LLM Models and Knowledge Base</figcaption></figure><p>In my <a href="https://medium.com/@alexander.uspensky/building-a-python-project-with-hugging-face-translation-model-using-fastapi-and-react-js-frontend-e0160156f4dd">previous article</a>, I explained how to create a simple translation API with a web interface using a free foundational LLM model. This time, let’s dive into building a Retrieval-Augmented Generation (RAG) system using free transformer-based LLM models and a knowledge base.</p><blockquote>RAG (Retrieval-Augmented Generation) is a technique that combines two key components:</blockquote><blockquote><strong>Retrieval</strong>: First, it searches through a knowledge base (like documents, databases, etc.) to find relevant information for a given query. This usually involves:</blockquote><blockquote>Converting text into embeddings (numerical vectors that represent meaning)</blockquote><blockquote>Finding similar content using similarity measures (like cosine similarity)</blockquote><blockquote>Selecting the most relevant pieces of information</blockquote><blockquote><strong>Generation</strong>: Then it uses a language model (like T5 in our code) to generate a response by:</blockquote><blockquote>Combining the retrieved information with the original question</blockquote><blockquote>Creating a natural language response based on this context</blockquote><p>In our code:</p><ul><li>The SentenceTransformer handles the retrieval part by creating embeddings</li><li>The T5 model handles the generation part by creating answers</li></ul><p>Benefits of RAG:</p><ul><li>More accurate responses since they’re grounded in specific knowledge</li><li>Reduced hallucination compared to pure LLM responses</li><li>Ability to access up-to-date or domain-specific information</li><li>More controllable and transparent than pure generation</li></ul><h3>System Architecture Overview</h3><p>The implementation consists of a SimpleQASystem class that orchestrates two main components:</p><ol><li>A semantic search system using Sentence Transformers</li><li>An answer generation system using T5</li></ol><blockquote>You can download the latest version of source code here: <a href="https://github.com/alexander-uspenskiy/rag_project">https://github.com/alexander-uspenskiy/rag_project</a></blockquote><h3><strong>System Diagram</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*9rONwgY7JGlveRNSNR_L8w.png" /><figcaption>System Diagram</figcaption></figure><h3>RAG Project Setup Guide</h3><p>This guide will help you set up your Retrieval-Augmented Generation (RAG) project on both macOS and Windows.</p><h3>Prerequisites</h3><h3>For macOS:</h3><ol><li>Install Homebrew (if not already installed):</li></ol><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><ol><li>Install Python 3.8+ using Homebrew</li></ol><pre>brew install python@3.10</pre><h3>For Windows:</h3><ol><li>Download and install Python 3.8+ from <a href="https://www.python.org/downloads/">python.org</a></li><li>Make sure to check “Add Python to PATH” during installation</li></ol><h3>Project Setup</h3><h3>Step 1: Create Project Directory</h3><p><strong>macOS:</strong></p><pre>mkdir RAG_project<br>cd RAG_project</pre><p><strong>Windows:</strong></p><pre>mkdir RAG_project<br>cd RAG_project</pre><h3>Step 2: Set Up Virtual Environment</h3><p><strong>macOS:</strong></p><pre>python3 -m venv venv<br>source venv/bin/activate</pre><p><strong>Windows:</strong></p><pre>python -m venv venv<br>venv\Scripts\activate</pre><h3>Core Components</h3><h3>1. Initialization</h3><pre>def __init__(self):<br>    self.model_name = &#39;t5-small&#39;<br>    self.tokenizer = T5Tokenizer.from_pretrained(self.model_name)<br>    self.model = T5ForConditionalGeneration.from_pretrained(self.model_name)<br>    self.encoder = SentenceTransformer(&#39;paraphrase-MiniLM-L6-v2&#39;)</pre><p>The system initializes with two primary models:</p><ul><li>T5-small: A smaller version of the T5 model for generating answers</li><li>paraphrase-MiniLM-L6-v2: A sentence transformer model for encoding text into meaningful vectors</li></ul><h3>2. Dataset Preparation</h3><pre>def prepare_dataset(self, data: List[Dict[str, str]]):<br>    self.answers = [item[&#39;answer&#39;] for item in data]<br>    self.answer_embeddings = []<br>    for answer in self.answers:<br>        embedding = self.encoder.encode(answer, convert_to_tensor=True)<br>        self.answer_embeddings.append(embedding)</pre><p>The dataset preparation phase:</p><ul><li>Extracts answers from the input data</li><li>Creates embeddings for each answer using the sentence transformer</li><li>Stores both answers and their embeddings for quick retrieval</li></ul><h3>How the System Works</h3><h3>1. Question Processing</h3><p>When a user submits a question, the system follows these steps:</p><p><strong>Embedding Generation</strong>: The question is converted into a vector representation using the same sentence transformer model used for the answers.</p><p><strong>Semantic Search</strong>: The system finds the most relevant stored answer by:</p><ul><li>Computing cosine similarity between the question embedding and all answer embeddings</li><li>Selecting the answer with the highest similarity score</li></ul><p><strong>Context Formation</strong>: The selected answer becomes the context for T5 to generate a final response.</p><h3>2. Answer Generation</h3><pre>def get_answer(self, question: str) -&gt; str:<br>    # ... semantic search logic ...<br>    input_text = f&quot;Given the context, what is the answer to the question: {question} Context: {context}&quot;<br>    input_ids = self.tokenizer(input_text, max_length=512, truncation=True, <br>                             padding=&#39;max_length&#39;, return_tensors=&#39;pt&#39;).input_ids<br>    outputs = self.model.generate(input_ids, max_length=50, num_beams=4, <br>                                early_stopping=True, no_repeat_ngram_size=2</pre><p>The answer generation process:</p><ol><li>Combines the question and context into a prompt for T5</li><li>Tokenizes the input text with a maximum length of 512 tokens</li><li>Generates an answer using beam search with these parameters:</li></ol><ul><li>max_length=50: Limits answer length</li><li>num_beams=4: Uses beam search with 4 beams</li><li>early_stopping=True: Stops generation when all beams reach an end token</li><li>no_repeat_ngram_size=2: Prevents repetition of bigrams</li></ul><h3>3. Answer Cleaning</h3><pre>def clean_answer(self, answer: str) -&gt; str:<br>    words = answer.split()<br>    cleaned_words = []<br>    for i, word in enumerate(words):<br>        if i == 0 or word.lower() != words[i-1].lower():<br>            cleaned_words.append(word)<br>    cleaned = &#39; &#39;.join(cleaned_words)<br>    return cleaned[0].upper() + cleaned[1:] if cleaned else cleaned</pre><ul><li>Removes duplicate consecutive words (case-insensitive)</li><li>Capitalizes the first letter of the answer</li><li>Removes extra whitespace</li></ul><h3><strong>Full Source Code</strong></h3><blockquote>You can download the latest version of source code here: <a href="https://github.com/alexander-uspenskiy/rag_project">https://github.com/alexander-uspenskiy/rag_project</a></blockquote><pre>import os<br># Set tokenizers parallelism before importing libraries<br>os.environ[&quot;TOKENIZERS_PARALLELISM&quot;] = &quot;false&quot;<br><br>import torch<br>from transformers import T5Tokenizer, T5ForConditionalGeneration<br>from typing import List, Dict<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>class SimpleQASystem:<br>    def __init__(self):<br>        &quot;&quot;&quot;Initialize QA system using T5&quot;&quot;&quot;<br>        try:<br>            # Use T5 for answer generation<br>            self.model_name = &#39;t5-small&#39;<br>            self.tokenizer = T5Tokenizer.from_pretrained(self.model_name, legacy=False)<br>            self.model = T5ForConditionalGeneration.from_pretrained(self.model_name)<br><br>            # Move model to CPU explicitly to avoid memory issues<br>            self.device = &quot;cpu&quot;<br>            self.model = self.model.to(self.device)<br><br>            # Initialize storage<br>            self.answers = []<br>            self.answer_embeddings = None<br>            self.encoder = SentenceTransformer(&#39;paraphrase-MiniLM-L6-v2&#39;)<br><br>            print(&quot;System initialized successfully&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Initialization error: {e}&quot;)<br>            raise<br><br>    def prepare_dataset(self, data: List[Dict[str, str]]):<br>        &quot;&quot;&quot;Prepare the dataset by storing answers and their embeddings&quot;&quot;&quot;<br>        try:<br>            # Store answers<br>            self.answers = [item[&#39;answer&#39;] for item in data]<br><br>            # Encode answers using SentenceTransformer<br>            self.answer_embeddings = []<br>            for answer in self.answers:<br>                embedding = self.encoder.encode(answer, convert_to_tensor=True)<br>                self.answer_embeddings.append(embedding)<br><br>            print(f&quot;Prepared {len(self.answers)} answers&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Dataset preparation error: {e}&quot;)<br>            raise<br><br>    def clean_answer(self, answer: str) -&gt; str:<br>        &quot;&quot;&quot;Clean up generated answer by removing duplicates and extra whitespace&quot;&quot;&quot;<br>        words = answer.split()<br>        cleaned_words = []<br>        for i, word in enumerate(words):<br>            if i == 0 or word.lower() != words[i-1].lower():<br>                cleaned_words.append(word)<br>        cleaned = &#39; &#39;.join(cleaned_words)<br>        return cleaned[0].upper() + cleaned[1:] if cleaned else cleaned<br><br>    def get_answer(self, question: str) -&gt; str:<br>        &quot;&quot;&quot;Get answer using semantic search and T5 generation&quot;&quot;&quot;<br>        try:<br>            if not self.answers or self.answer_embeddings is None:<br>                raise ValueError(&quot;Dataset not prepared. Call prepare_dataset first.&quot;)<br><br>            # Encode question using SentenceTransformer<br>            question_embedding = self.encoder.encode(<br>                question,<br>                convert_to_tensor=True,<br>                show_progress_bar=False<br>            )<br><br>            # Move the question embedding to CPU (if not already)<br>            question_embedding = question_embedding.cpu()<br><br>            # Find most similar answer using cosine similarity<br>            similarities = cosine_similarity(<br>                question_embedding.numpy().reshape(1, -1),  # Use .numpy() for numpy compatibility<br>                np.array([embedding.cpu().numpy() for embedding in self.answer_embeddings])  # Move answer embeddings to CPU<br>            )[0]<br><br>            best_idx = np.argmax(similarities)<br>            context = self.answers[best_idx]<br><br>            # Generate the input text for the T5 model<br>            input_text = f&quot;Given the context, what is the answer to the question: {question} Context: {context}&quot;<br>            print(input_text)<br>            # Tokenize input text<br>            input_ids = self.tokenizer(<br>                input_text,<br>                max_length=512,<br>                truncation=True,<br>                padding=&#39;max_length&#39;,<br>                return_tensors=&#39;pt&#39;<br>            ).input_ids.to(self.device)<br><br>            # Generate answer with limited max_length<br>            outputs = self.model.generate(<br>                input_ids,<br>                max_length=50,  # Increase length to handle more detailed answers<br>                num_beams=4,<br>                early_stopping=True,<br>                no_repeat_ngram_size=2<br>            )<br><br>            # Decode the generated answer<br>            answer = self.tokenizer.decode(outputs[0], skip_special_tokens=True)<br><br>            # Print the raw generated answer for debugging<br>            print(f&quot;Generated answer before cleaning: {answer}&quot;)<br><br>            # Clean up the answer<br>            cleaned_answer = self.clean_answer(answer)<br>            return cleaned_answer<br><br>        except Exception as e:<br>            print(f&quot;Error generating answer: {e}&quot;)<br>            return f&quot;Error: {str(e)}&quot;<br><br><br>def main():<br>    &quot;&quot;&quot;Main function with sample usage&quot;&quot;&quot;<br>    try:<br>        # Sample data<br>        data = [<br>            {&quot;question&quot;: &quot;What is the capital of France?&quot;, &quot;answer&quot;: &quot;The capital of France is Paris.&quot;},<br>            {&quot;question&quot;: &quot;What is the largest planet?&quot;, &quot;answer&quot;: &quot;The largest planet is Jupiter.&quot;},<br>            {&quot;question&quot;: &quot;Who wrote &#39;1984&#39;?&quot;, &quot;answer&quot;: &quot;George Orwell wrote &#39;1984&#39;.&quot;}<br>        ]<br><br>        # Initialize system<br>        print(&quot;Initializing QA system...&quot;)<br>        qa_system = SimpleQASystem()<br><br>        # Prepare dataset<br>        print(&quot;Preparing dataset...&quot;)<br>        qa_system.prepare_dataset(data)<br><br>        # Start interactive Q&amp;A session<br>        while True:<br>            # Prompt the user for a question<br>            test_question = input(&quot;\nPlease enter your question (or &#39;exit&#39; to quit): &quot;)<br><br>            if test_question.lower() == &#39;exit&#39;:<br>                print(&quot;Exiting the program.&quot;)<br>                break<br><br>            # Get and print the answer<br>            print(f&quot;\nQuestion: {test_question}&quot;)<br>            answer = qa_system.get_answer(test_question)<br>            print(f&quot;Answer: {answer}&quot;)<br><br>    except Exception as e:<br>        print(f&quot;Error in main: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()Performance Considerations</pre><p><strong>Memory Management</strong>:</p><ul><li>The system explicitly uses CPU to avoid memory issues</li><li>Embeddings are converted to CPU tensors when needed</li><li>Input length is limited to 512 tokens</li></ul><p><strong>Error Handling</strong>:</p><ul><li>Comprehensive try-except blocks throughout the code</li><li>Meaningful error messages for debugging</li><li>Validation checks for uninitialized components</li></ul><h3>Usage Example</h3><pre># Initialize system<br>qa_system = SimpleQASystem()</pre><pre># Prepare sample data<br>data = [<br>    {&quot;question&quot;: &quot;What is the capital of France?&quot;, &quot;answer&quot;: &quot;The capital of France is Paris.&quot;},<br>    {&quot;question&quot;: &quot;What is the largest planet?&quot;, &quot;answer&quot;: &quot;The largest planet is Jupiter.&quot;}<br>]</pre><pre># Prepare dataset<br>qa_system.prepare_dataset(data)</pre><pre># Get answer<br>answer = qa_system.get_answer(&quot;What is the capital of France?&quot;)</pre><h3>Run in terminal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*-XEgx5HSQ7eXuyx5KdnjgQ.png" /><figcaption>Run in terminal</figcaption></figure><h3>Limitations and Potential Improvements</h3><p><strong>Scalability</strong>:</p><ul><li>The current implementation keeps all embeddings in memory</li><li>Could be improved with vector databases for large-scale applications</li></ul><p><strong>Answer Quality</strong>:</p><ul><li>Relies heavily on the quality of the provided answer dataset</li><li>Limited by the context window of T5-small</li><li>Could benefit from answer validation or confidence scoring</li></ul><p><strong>Performance</strong>:</p><ul><li>Using CPU only might be slower for large-scale applications</li><li>Could be optimized with batch processing</li><li>Could implement caching for frequently asked questions</li></ul><h3>Conclusion</h3><blockquote>This implementation provides a solid foundation for a question-answering system, combining the strengths of semantic search and transformer-based text generation. Feel free to play with model parameters (like max_length, num_beams, early_stopping, no_repeat_ngram_size, etc) to find a better way to get more coherent and stable answers. While there’s room for improvement, the current implementation offers a good balance between complexity and functionality, making it suitable for educational purposes and small to medium-scale applications.</blockquote><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea9185ff96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Python Project with Hugging Face Translation Model Using FastAPI and React JS Frontend…]]></title>
            <link>https://alexander-uspenskiy.medium.com/building-a-python-project-with-hugging-face-translation-model-using-fastapi-and-react-js-frontend-e0160156f4dd?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0160156f4dd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 17:50:59 GMT</pubDate>
            <atom:updated>2024-10-28T17:22:22.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Python Project with Hugging Face Translation Model Using FastAPI and React JS Frontend: Performance Analysis and Estimation</h3><figure><img alt="Building a Python Project with Hugging Face Translation Model Using FastAPI and React JS Frontend: Performance Analysis and Estimation" src="https://cdn-images-1.medium.com/max/1024/1*3XGggbg8mlvt0GPbwDYyWQ.jpeg" /></figure><p><strong>Quick summary:</strong></p><blockquote><em>This article outlines the process of creating a client (using React JS, Vite, and TypeScript) and a server (utilizing Python FastAPI, the Transformers library, and the Helsinki-NLP translation model) to demonstrate and analyze the performance of the translation model in real-time applications.</em></blockquote><p><strong>About model:</strong></p><p>The <strong>Helsinki-NLP translation models</strong> are part of the Hugging Face model hub, created by the University of Helsinki’s Natural Language Processing (NLP) group. These models are based on the <strong>MarianMT</strong> framework, a highly efficient machine translation model designed for multiple languages.</p><p>These models, like <strong>opus-mt-en-fr</strong> (English to French) or <strong>opus-mt-fr-en</strong> (French to English), are trained on the <strong>OPUS corpus</strong>, a multilingual dataset containing parallel text data from various sources. They support translations between many languages, especially low-resource ones, and are pre-trained using a <strong>transformer architecture</strong>.</p><p><strong>Key aspects:</strong></p><ul><li><strong>Wide language support</strong>: Can handle many language pairs, including low-resource languages.</li><li><strong>Performance</strong>: Optimized for translation tasks in real-time applications.</li><li><strong>Model availability</strong>: These models are available for free on the Hugging Face Model Hub, where users can easily integrate them into their projects using libraries like transformers.</li></ul><p>These models are commonly used in academic research, multilingual NLP applications, and real-time translation systems.</p><p>For more details, you can explore the models on the Hugging Face platform: <a href="https://huggingface.co/Helsinki-NLP">Hugging Face Helsinki-NLP models</a>.</p><p>Let’s start with FastAPI backend (server side):</p><pre>mkdir huggingface_translation<br>cd huggingface_translation</pre><p>Create a virtual environment:</p><pre>python3 -m venv venv<br>source venv/bin/activate</pre><p>Install the required packages:</p><pre>pip install transformers torch sentencepiece sacremoses psutil</pre><p>Now, let’s create a simple Python script that uses a Hugging Face translation model with some additional performance metrics (memory and execution time):</p><pre><br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from fastapi.concurrency import run_in_threadpool<br>import torch<br>import psutil<br>import os<br>import time<br>from transformers import pipeline<br><br>app = FastAPI()<br><br>def get_size(bytes, suffix=&quot;B&quot;):<br>    <br>    factor = 1024<br>    for unit in [&quot;&quot;, &quot;K&quot;, &quot;M&quot;, &quot;G&quot;, &quot;T&quot;, &quot;P&quot;]:<br>        if bytes &lt; factor:<br>            return f&quot;{bytes:.2f}{unit}{suffix}&quot;<br>        bytes /= factor<br><br>def translate(text, src_lang=&quot;en&quot;, tgt_lang=&quot;fr&quot;):<br>    <br>    device = 0 if torch.cuda.is_available() else -1<br>    <br>    start_time = time.time()<br>    if torch.cuda.is_available():<br>        torch.cuda.reset_peak_memory_stats()<br>        start_mem = torch.cuda.memory_allocated()<br>    else:<br>        process = psutil.Process(os.getpid())<br>        start_mem = process.memory_info().rss<br><br>    translator = pipeline(&quot;translation&quot;, model=f&quot;Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}&quot;, device=device)<br>    translated = translator(text, max_length=40)[0][&#39;translation_text&#39;]<br><br>    end_time = time.time()<br>    if torch.cuda.is_available():<br>        end_mem = torch.cuda.max_memory_allocated()<br>        mem_diff = end_mem - start_mem<br>    else:<br>        end_mem = process.memory_info().rss<br>        mem_diff = end_mem - start_mem<br><br>    computation_time = end_time - start_time<br><br>    return translated, get_size(mem_diff), computation_time<br><br>class TranslationRequest(BaseModel):<br>    text: str<br>    src_lang: str = &quot;en&quot;<br>    tgt_lang: str = &quot;fr&quot;<br><br>@app.post(&quot;/translate&quot;)<br>async def translate_text(req: TranslationRequest):<br>    translated_text, memory_used, comp_time = await run_in_threadpool(translate, req.text, req.src_lang, req.tgt_lang)<br>    response = {<br>        &quot;original_text&quot;: req.text,<br>        &quot;translated_text&quot;: translated_text,<br>        &quot;memory_used&quot;: memory_used,<br>        &quot;computation_time&quot;: f&quot;{comp_time:.2f} seconds&quot;,<br>        &quot;device&quot;: &quot;GPU&quot; if torch.cuda.is_available() else &quot;CPU&quot;<br>    }<br>    return response</pre><p>This code demonstrates a FastAPI-based backend service that translates text using the Hugging Face <strong>transformers</strong> library. It implements the Helsinki-NLP translation models, allowing translation between different language pairs. Here’s a breakdown:</p><ul><li><strong>Memory Tracking and Performance Monitoring</strong>: The translate function calculates memory usage and execution time for the translation operation, supporting both GPU and CPU processing.</li><li><strong>FastAPI POST Route</strong>: The /translate endpoint accepts a POST request with text, src_lang, and tgt_lang. It calls the translation function, logs memory used, translation time, and whether the operation used GPU or CPU.</li><li><strong>Dependencies</strong>: Includes torch for GPU computation, psutil for memory usage stats, and transformers for the translation pipeline.</li><li><strong>run_in_threadpool</strong>: This method is used to execute synchronous functions within an asynchronous context, without blocking the event loop. It moves the CPU-bound translate function to a separate thread.</li><li><strong>Async Route</strong>: The route remains asynchronous, allowing FastAPI to continue handling other requests while the translation runs.This API is optimized for performance tracking, with data being returned to clients about the translation, computation time, and device used (GPU/CPU).</li></ul><p>To run the backend:</p><pre>uvicorn huggingface_translation:app --reload</pre><p>Let’s proceed with Frontend (TypeScript) Client side:</p><pre>npm create vite@latest my-react-app -- --template react-ts<br>cd my-react-app<br>npm install</pre><p>Update App.tsx (in src directory)</p><pre>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br><br>// Define the interface for the request data structure<br>interface TranslateRequest {<br>  text: string;<br>  src_lang: string;<br>  tgt_lang: string;<br>}<br><br>// Define an array of language options<br>const languageOptions = [<br>  { code: &#39;en&#39;, name: &#39;English&#39; },<br>  { code: &#39;fr&#39;, name: &#39;French&#39; },<br>  { code: &#39;es&#39;, name: &#39;Spanish&#39; },<br>  { code: &#39;de&#39;, name: &#39;German&#39; },<br>  { code: &#39;zh&#39;, name: &#39;Chinese&#39; },<br>  { code: &#39;ru&#39;, name: &#39;Russian&#39; },<br>  // Add more languages as needed<br>];<br><br>const App = () =&gt; {<br>  const [text, setText] = useState&lt;string&gt;(&#39;&#39;);<br>  const [srcLang, setSrcLang] = useState&lt;string&gt;(&#39;en&#39;); // State for source language<br>  const [tgtLang, setTgtLang] = useState&lt;string&gt;(&#39;fr&#39;); // State for target language<br>  const [translated, setTranslated] = useState&lt;string&gt;(&#39;&#39;);<br><br>  const handleSubmit = async (event: React.FormEvent) =&gt; {<br>    event.preventDefault();<br>    console.log(&quot;Form submitted with text:&quot;, text); // Log the input text<br><br>    // Create the request data based on the interface<br>    const requestData: TranslateRequest = {<br>      text,<br>      src_lang: srcLang, // Use the source language from state<br>      tgt_lang: tgtLang, // Use the target language from state<br>    };<br><br>    const response = await fetch(&#39;/api/translate&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body: JSON.stringify(requestData), // Use requestData here<br>    });<br><br>    if (!response.ok) {<br>      console.error(&quot;Error in response:&quot;, response); // Log response if not ok<br>      return;<br>    }<br><br>    const data = await response.json();<br>    console.log(&quot;Translated text received:&quot;, data.translated_text);<br>    setTranslated(data.translated_text);<br>  };<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={text}<br>          onChange={(e) =&gt; setText(e.target.value)}<br>          placeholder=&quot;Enter text to translate&quot;<br>        /&gt;<br>        &lt;br&gt;&lt;/br&gt;<br>        {/* Dropdown for source language selection */}<br>        From: &lt;select value={srcLang} onChange={(e) =&gt; setSrcLang(e.target.value)}&gt;<br>          {languageOptions.map((lang) =&gt; (<br>            &lt;option key={lang.code} value={lang.code}&gt;<br>              {lang.name}<br>            &lt;/option&gt;<br>          ))}<br>        &lt;/select&gt;<br>        &lt;br&gt;&lt;/br&gt;<br>        {/* Dropdown for target language selection */}<br>        To: &lt;select value={tgtLang} onChange={(e) =&gt; setTgtLang(e.target.value)}&gt;<br>          {languageOptions.map((lang) =&gt; (<br>            &lt;option key={lang.code} value={lang.code}&gt;<br>              {lang.name}<br>            &lt;/option&gt;<br>          ))}<br>        &lt;/select&gt;<br>        &lt;br&gt;&lt;/br&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Translate&lt;/button&gt;<br>      &lt;/form&gt;<br>      &lt;p&gt;{translated}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App; // Exporting as default</pre><p>This React app allows users to input text, select source and target languages from dropdowns, and submit the text for translation. It uses useState hooks to manage the input text, source language, target language, and translated text. When the form is submitted, a POST request is sent to a backend API (/api/translate), which processes the translation and returns the result. The app displays the translated text after receiving the response.</p><p>The code includes:</p><ul><li><strong>TranslateRequest Interface</strong>: Defines the structure of the data sent to the API (text, source language, target language).</li><li><strong>Language Selection</strong>: A dropdown menu allows users to choose the source and target languages dynamically.</li><li><strong>State Management</strong>: The useState hook is used for handling text input, language selection, and translated text.</li></ul><p>Just add proxy to proceed with /api/ path correctly in vite.config.ts:</p><pre>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  plugins: [react()],<br>  server: {<br>    proxy: {<br>      &#39;/api&#39;: {<br>        target: &#39;http://127.0.0.1:8000&#39;,<br>        changeOrigin: true,<br>        rewrite: (path) =&gt; path.replace(/^\/api/, &#39;&#39;)<br>      }<br>    }<br>  }<br>});</pre><p>Run the app</p><pre>npm run dev</pre><p>What you should see in the browser windows (mind the port name in terminal window)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKlIMj0j2WShHcAyTH80-Q.png" /><figcaption>.Source text and translated result (english to french)</figcaption></figure><p>Let’s check the performance (MacBook Pro M1Max, GPU not supported):</p><p>Use <a href="http://127.0.0.1:8000/docs#/default">http://127.0.0.1:8000/docs#/default</a> for Swager (thanks to FastAPI Swagger available by default so no new code needed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OWhMJFavZygHk2kVmKgcw.png" /><figcaption>Request with text and language selections</figcaption></figure><p>And result, not too bad, under 2 sec:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7kJKkwEGgDG5_9epmYDIA.png" /><figcaption>Result of translation and metrics</figcaption></figure><p>Once the translation model is loaded, subsequent translations might not require loading the full model into memory again. This means that only minimal memory is allocated during translation, which results in low memory usage for each translation task after the initial load.</p><p>Time to execute raw data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*mf40YKuzg9mqE0JbC8JcOQ.png" /></figure><p>Basic visualisation and analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*EyyYbgB_I0lHtJcVhhxXAA.png" /></figure><p>As you can see there is a close to linear function of text lengths vs execute time which is expected from Helsinki-NLP translation model</p><p><strong>Summary:</strong></p><blockquote>In this article we’ve created client (React JS, Vite, TypeScript) and Server (Python FastAPI, Transformers library, Helsinki-NLP translation model) and analyzed performance of this solution.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0160156f4dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web 3.0. that is this buzzword about?]]></title>
            <link>https://alexander-uspenskiy.medium.com/web-3-0-that-is-this-buzzword-about-f3f95696cc20?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f95696cc20</guid>
            <category><![CDATA[web3-0]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 21:39:47 GMT</pubDate>
            <atom:updated>2024-09-05T21:39:47.691Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Web 3.0</strong>, often referred to as the “decentralized web” or “semantic web,” represents the next generation of the internet, building on the foundations of Web 2.0 (the social web). The primary concept of Web 3.0 is to create a more intelligent, open, and user-centric internet that enables users to interact directly with each other without relying on central authorities or intermediaries. Here are the basic concepts of Web 3.0:</p><h3>1. Decentralization</h3><ul><li><strong>Peer-to-Peer (P2P) Networks</strong>: Unlike Web 2.0, which is largely controlled by centralized entities like Facebook, Google, and Amazon, Web 3.0 leverages decentralized networks. Data is stored across a distributed network of computers (nodes) rather than on a central server. This reduces dependency on centralized platforms and mitigates issues related to data privacy, security, and control.</li><li><strong>Blockchain Technology</strong>: Web 3.0 heavily relies on blockchain, a decentralized ledger technology that ensures data transparency, security, and immutability. Blockchain enables trustless transactions, meaning transactions are verified and recorded without needing a trusted third party.</li></ul><h3>2. Data Ownership and Privacy</h3><ul><li><strong>User Control over Data</strong>: In Web 3.0, users have greater control over their data. Instead of companies owning and monetizing user data, individuals can choose how their data is shared, who it’s shared with, and how it’s used. This shift empowers users with privacy and control.</li><li><strong>Self-Sovereign Identity</strong>: Users can manage their digital identities independently without needing centralized authorities like governments or corporations. This concept ensures privacy and security, enabling users to control access to their identity information.</li></ul><h3>3. Semantic Web</h3><ul><li><strong>Improved Data Interconnectivity</strong>: Web 3.0 aims to make data more accessible and meaningful. The semantic web enhances the ability of machines to understand and interpret the data on the internet, making it easier to find, share, and reuse information across different applications and platforms.</li><li><strong>AI and Machine Learning</strong>: These technologies play a significant role in Web 3.0 by providing more personalized and intelligent search results and services. They can analyze vast amounts of data, learn from it, and offer tailored experiences based on user behavior and preferences.</li></ul><h3>4. Interoperability and Composability</h3><ul><li><strong>Cross-Platform Integration</strong>: Web 3.0 promotes interoperability, meaning different platforms, applications, and services can seamlessly interact with each other. This fosters a more integrated and interconnected digital ecosystem.</li><li><strong>Composable Applications</strong>: Applications in Web 3.0 are designed to be modular and reusable, allowing developers to build on top of existing applications and services easily. This composability accelerates innovation and reduces redundancy.</li></ul><h3>5. Trustless and Permissionless Networks</h3><ul><li><strong>Trustless Systems</strong>: Web 3.0 eliminates the need for intermediaries (like banks or tech companies) to facilitate transactions or data exchanges. It uses smart contracts, which are self-executing contracts with the terms directly written into code, to automate and enforce agreements transparently and securely.</li><li><strong>Permissionless Access</strong>: Anyone can participate in Web 3.0 networks without needing authorization from a central authority. This openness democratizes access to information and services, fostering a more inclusive internet.</li></ul><h3>6. Decentralized Applications (dApps)</h3><ul><li><strong>dApps</strong>: Decentralized applications (dApps) are applications that run on a blockchain or P2P network rather than a single server. They are open-source, and their operations are transparent, autonomous, and resistant to censorship. Examples include decentralized finance (DeFi) apps, decentralized social networks, and decentralized marketplaces.</li></ul><p><strong>Web 3.0 architecture</strong> is built on a decentralized and distributed model that integrates various technologies to create a more intelligent, secure, and user-centric internet. Here is a breakdown of the main components and layers of Web 3.0 architecture:</p><h3>1. Blockchain Layer</h3><ul><li><strong>Distributed Ledger Technology (DLT)</strong>: This is the foundational layer of Web 3.0, where data is stored across a distributed network of nodes (computers). Blockchain technology is a type of DLT that maintains a decentralized and immutable ledger of transactions.</li><li><strong>Consensus Mechanisms</strong>: These are protocols used by blockchain networks to validate transactions and maintain agreement across the network. Examples include Proof of Work (PoW), Proof of Stake (PoS), and Delegated Proof of Stake (DPoS). These mechanisms ensure the security and integrity of the blockchain without needing a centralized authority.</li><li><strong>Smart Contracts</strong>: Smart contracts are self-executing contracts with the terms directly written into code on the blockchain. They automatically enforce and execute agreements when predefined conditions are met, enabling trustless and automated transactions.</li></ul><h3>2. Decentralized Storage Layer</h3><ul><li><strong>Distributed File Storage</strong>: Instead of relying on centralized servers, Web 3.0 uses decentralized storage solutions like IPFS (InterPlanetary File System), Arweave, and Filecoin. These systems store files across a network of nodes, making data more secure, resilient, and censorship-resistant.</li><li><strong>Data Availability and Redundancy</strong>: Decentralized storage ensures data availability and redundancy by distributing copies of data across multiple nodes. This reduces the risk of data loss and enhances access speed and reliability.</li></ul><h3>3. Decentralized Network Layer</h3><ul><li><strong>Peer-to-Peer (P2P) Networks</strong>: Web 3.0 leverages P2P networks to enable direct communication and data exchange between users without intermediaries. This architecture enhances privacy, reduces latency, and distributes bandwidth more efficiently.</li><li><strong>Decentralized Identity (DID)</strong>: This component allows users to have self-sovereign identities, meaning they control their digital identities without relying on centralized authorities. DID frameworks like Sovrin and uPort provide users with a secure, private way to manage their identity and credentials.</li></ul><h3>4. Protocol Layer</h3><ul><li><strong>Interoperability Protocols</strong>: Web 3.0 emphasizes interoperability, allowing different blockchains and decentralized applications (dApps) to communicate and interact seamlessly. Protocols like Polkadot, Cosmos, and Chainlink facilitate interoperability by enabling cross-chain communication and data sharing.</li><li><strong>Decentralized Finance (DeFi) Protocols</strong>: DeFi protocols allow for decentralized financial services such as lending, borrowing, trading, and staking. Examples include Uniswap, Compound, and Aave, which operate without intermediaries and provide users with greater control over their assets.</li></ul><h3>5. Application Layer</h3><ul><li><strong>Decentralized Applications (dApps)</strong>: dApps are applications that run on a blockchain network rather than a centralized server. They are open-source, transparent, and resistant to censorship. Examples include decentralized exchanges (DEXs), social networks, gaming platforms, and NFT marketplaces.</li><li><strong>User Interfaces (UIs)</strong>: The application layer includes UIs that allow users to interact with dApps and blockchain networks. Web 3.0 UIs are often web-based, using decentralized web technologies such as React.js or Vue.js, with backend services connected to blockchain networks via APIs.</li></ul><h3>6. Security and Privacy Layer</h3><ul><li><strong>Encryption and Privacy Protocols</strong>: Web 3.0 incorporates advanced encryption techniques and privacy protocols to protect user data and ensure secure transactions. Zero-knowledge proofs (ZKPs), such as zk-SNARKs and zk-STARKs, enable private transactions and data verification without revealing sensitive information.</li><li><strong>Security Mechanisms</strong>: These include multisignature wallets, decentralized authentication, and hardware wallets, which provide enhanced security for users’ assets and interactions in the Web 3.0 environment.</li></ul><h3>7. AI and Machine Learning Layer</h3><ul><li><strong>Data Analysis and Personalization</strong>: Web 3.0 utilizes AI and machine learning algorithms to analyze vast amounts of decentralized data. This analysis can provide personalized content, improve user experience, and enable more intelligent decision-making processes.</li><li><strong>Semantic Web Technologies</strong>: The use of AI helps in creating a semantic web where machines understand and interpret the context and meaning of data, allowing for more intuitive search and interaction experiences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0WFYYrPOqPOuJK56tAnTw.png" /><figcaption>Basic Architecture of Web3.0 Apps</figcaption></figure><h3>Summary</h3><p>Web 3.0 represents a shift towards a more decentralized, user-centric, and intelligent internet. By leveraging blockchain, AI, and machine learning, Web 3.0 aims to provide more control to users over their data and privacy while enabling more seamless and meaningful interactions across the digital landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f95696cc20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Little Book of f-Laws: 13 Common Sins of Management]]></title>
            <link>https://alexander-uspenskiy.medium.com/a-little-book-of-f-laws-13-common-sins-of-management-77f29e8d35da?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f29e8d35da</guid>
            <category><![CDATA[management]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 16:14:22 GMT</pubDate>
            <atom:updated>2024-08-09T16:14:22.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*xoWL77ha-zXZDeTN2A4vBg.jpeg" /></figure><p><em>A Little Book of f-Laws: 13 Common Sins of Management</em> is a compilation of management insights and “f-Laws” (flaws in laws) from Russell Ackoff, a pioneer in systems thinking and organizational theory. The book highlights common pitfalls and misguided beliefs in management practices, challenging conventional wisdom with a blend of humor and critical thinking.</p><p>Here’s a summary of the key points:</p><ol><li><strong>The illusion of control</strong>: Managers often believe they have more control over their organizations than they actually do. Real control is limited and often illusory.</li><li><strong>Focus on efficiency over effectiveness</strong>: Managers may focus on doing things right rather than doing the right things. This leads to optimized processes that don’t necessarily achieve the desired outcomes.</li><li><strong>Short-term thinking</strong>: The pressure for immediate results can lead to decisions that undermine long-term success. A lack of foresight is a common managerial flaw.</li><li><strong>The misuse of measurement</strong>: Management often relies too heavily on metrics and quantifiable data, which can lead to a focus on what is easy to measure rather than what is important.</li><li><strong>Overemphasis on hierarchical structures</strong>: The rigid adherence to hierarchical management structures can stifle creativity and innovation. Organizations often suffer from a lack of communication and collaboration across levels.</li><li><strong>Misplaced motivation</strong>: Traditional incentives and rewards often fail to motivate employees effectively. Management’s misunderstanding of what drives human behavior leads to ineffective motivation strategies.</li><li><strong>The failure to recognize interdependencies</strong>: Managers often fail to see the interconnectedness of various parts of the organization, leading to decisions that benefit one area at the expense of another.</li><li><strong>Resistance to change</strong>: Change is often resisted due to fear and uncertainty, but this resistance can be exacerbated by management’s failure to engage and involve employees in the change process.</li><li><strong>Lack of innovation</strong>: Management’s fear of failure can stifle innovation. Organizations need to create environments where experimentation and failure are seen as part of the learning process.</li><li><strong>The myth of best practices</strong>: The belief in universally applicable best practices can be misguided. What works in one context may not work in another.</li><li><strong>The pursuit of perfection</strong>: The quest for perfection can be paralyzing. Organizations should instead focus on continuous improvement and learning.</li><li><strong>Over-reliance on experts</strong>: While expertise is valuable, over-reliance on experts can lead to a lack of diverse perspectives and innovative thinking.</li><li><strong>The false sense of security</strong>: Managers often believe that following procedures and protocols ensures success, but this can create a false sense of security. Flexibility and adaptability are crucial.</li></ol><p>Ackoff’s book encourages managers to think critically about their practices and to challenge the conventional wisdom that often guides their decisions. It’s a call for more thoughtful, holistic, and systemic approaches to management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f29e8d35da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ideal ChatBot for eCommerce]]></title>
            <link>https://alexander-uspenskiy.medium.com/ideal-chatbot-for-ecommerce-841603ff95c5?source=rss-9a952b164da0------2</link>
            <guid isPermaLink="false">https://medium.com/p/841603ff95c5</guid>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alexander Uspenskiy]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 17:46:30 GMT</pubDate>
            <atom:updated>2024-08-08T17:46:30.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e575EOffHgzpLM5uj2zKQw.jpeg" /><figcaption>ChatBot</figcaption></figure><p>Let’s envision an ‘ideal’ chatbot that genuinely enhances the e-commerce experience. This advanced AI assistant would be capable of guiding you seamlessly through the ordering process and adeptly handling complex inquiries. Unlike basic chatbots, this ideal system would offer personalized support, understand context, and provide solutions to intricate problems. It would combine the efficiency of automation with the nuanced understanding typically associated with human customer service representatives.</p><p>Such a chatbot would integrate seamlessly with the e-commerce platform, accessing real-time inventory data, order history, and user preferences. It could offer product recommendations, troubleshoot issues, process returns, and even anticipate customer needs based on browsing behavior and past interactions.</p><p>The architecture of this ideal chatbot would include advanced natural language processing, a robust knowledge base, machine learning capabilities for continuous improvement, and seamless integration with backend systems.</p><figure><img alt="Chatbot for eCommerce" src="https://cdn-images-1.medium.com/max/720/1*8lz6PiNb_Myk5jxY1t20Wg.png" /></figure><p>Here is an advanced chatbot system designed to provide comprehensive assistance in e-commerce. The diagram illustrates several crucial components that work together to create a highly effective customer service tool:</p><ol><li>NLP Layer: Processes natural language input from customers, translating it into actionable instructions for the chatbot engine.</li><li>ML Layer: Continuously learns and improves models based on new data and interactions.</li><li>Storage Layer: Maintains conversation history and stores any customer-specific issue cases for future reference.</li><li>Knowledge Base: Contains FAQs and other information to generate personalized responses using context and customer data.</li><li>Security Layer: Controls data access, ensuring sensitive customer information is protected.</li><li>Identity Manager: Handles account-related operations like password resets and troubleshooting.</li><li>CRM System: Provides comprehensive customer profile information.</li><li>OMS (Order Management System): Accesses real-time order status information to answer related queries.</li><li>IT Helpdesk and Human Operators: Available for escalation when the chatbot cannot resolve an issue.</li></ol><p>This architecture enables the chatbot to handle a wide range of tasks, from simple inquiries to complex problem-solving, while maintaining security and personalization. It represents a significant advancement over basic chatbots, potentially transforming the e-commerce customer service experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841603ff95c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>