<?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 Aditya Bahl on Medium]]></title>
        <description><![CDATA[Stories by Aditya Bahl on Medium]]></description>
        <link>https://medium.com/@aditya.addy.bahl?source=rss-5482e6712265------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xxCh3LFRs_7P0e9fjE-s1g.jpeg</url>
            <title>Stories by Aditya Bahl on Medium</title>
            <link>https://medium.com/@aditya.addy.bahl?source=rss-5482e6712265------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:56:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aditya.addy.bahl/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[Aditya’s Top AI Predictions for 2026]]></title>
            <link>https://medium.com/@aditya.addy.bahl/adityas-top-ai-predictions-for-2026-ff2838703fa5?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2838703fa5</guid>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 03:06:20 GMT</pubDate>
            <atom:updated>2026-01-05T03:06:20.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZdB64y5CgS-dqYPGLpzDw.png" /></figure><p>Happy New Year and welcome to 2026! In 2025, we witnessed AI hype evolve into tangible results — startups scaled from $0 to $100M in revenue at unprecedented speed, and enterprises began embedding AI into real workflows. Yet 2025 also revealed new challenges, from infrastructure bottlenecks to calls for greater AI accountability. Now, 2026 promises to be the year AI truly “grows up,” moving from pilots and demos to widespread production use, forging new business models, and confronting its practical limits. Here are my top 10 predictions for AI in 2026:</p><h3>1. Enterprise AI moves from pilots to production</h3><p>2026 is the year enterprise AI stops being a side project. Enterprises have moved past being impressed by demos. They want AI that’s seamlessly embedded into how work already gets done, so teams don’t have to switch tools, copy paste context, or babysit a chatbot. If AI creates friction, adoption dies. If it removes friction, it spreads.</p><p>Implementation preference will split the market. The most technical enterprises will want a composable platform to build and iterate on agents. But most organizations don’t want to staff an “agent engineering” function. They want AI to show up like software usually does: configured to their workflows, integrated to their systems, and supported like a real production product — not a kit of parts.</p><p>Production success will come down to reliability and governance. That means deep integrations, robust handling of the long tail of edge cases, and strong guardrails. The vendors that win in 2026 will be the ones that make AI feel boringly dependable — clear observability, auditable actions, easy controls — so enterprise teams can deploy agents broadly without fear.</p><h3>2. Reimagining the System of Record: Decision Traces Take Over</h3><p>In an agentic world, the UI changes first: agents become the interface for work. But the deeper shift in 2026 is what sits underneath. The old system of record captured the outcome. The new system of record captures the decision process — the context pulled from multiple systems, the rules applied, the exceptions handled, and the approvals triggered.</p><p>This doesn’t kill CRMs or ERPs, but it changes what “good” looks like. Enterprises will demand systems that provide observability by default: decision traces, policy enforcement, and the ability to replay what happened when something goes wrong. The competitive moat shifts from “who has the most data” to “who has the best trace of decisions and operations.”</p><p>Agents can be the front door, but trust lives in the foundation. The platforms that win will be the ones that combine clean underlying records with a traceable execution layer that can prove, step by step, how outcomes were produced.</p><h3>3. Voice AI Agents Move From Scripts to Systems</h3><p>Voice AI agents used to be glorified scripts: answer a few FAQs, route a call, maybe book an appointment if the path is simple. In 2026, they move from “talking” to doing. The call becomes the interface, but the real value is the agent completing the workflow end to end: pulling context, applying rules, updating systems, and handing off cleanly when a human is needed.</p><p>This is why voice becomes such a powerful enterprise surface area. The phone is still where the highest urgency, highest emotion, and highest volume interactions happen, especially in healthcare. If you can make every call shorter, more accurate, and more consistent, you improve customer experience and operational efficiency at the same time.</p><p>The winners won’t be the teams with the most human sounding voice, they’ll be the teams with the deepest system integration. Voice agents that connect to scheduling, ticketing, billing, CRM, and EHR adjacent workflows will feel less like call center automation and more like a new operating layer. Voice is the front door, but systems are the foundation.</p><h3>4. Moving Past the Prompt Box: The New Agentic UI</h3><p>The prompt box is powerful, but it’s a temporary interface. In 2026, AI moves from “answering” to “operating,” and that requires a different UI. Agents will be embedded into workflows and will surface the right options at the right moment — based on context, policies, and what’s pending — rather than waiting for a user to ask.</p><p>A practical way to think about it is this: the agentic UI is a stream of decisions. The agent proposes actions with explanations and previews, the human approves or edits, and the system records what happened. It’s an assembly line of work, not a chat session. That’s how you scale AI inside organizations without chaos.</p><p>The best implementations will make the handoffs clean and the system trustworthy. Persistent state, clear audit trails, and controlled permissions will be built into the experience. You won’t “talk to the AI,” you’ll simply see work moving forward — with the agent doing the heavy lifting in the background.</p><h3>5. Incentives Finally Match: Paying for Outcomes</h3><p>Seat-based pricing breaks when software starts doing the work. In 2026, outcome-based pricing becomes more mainstream because it matches how buyers actually think: pay me for impact, not access. Enterprises don’t want another subscription line item — they want a business case they can defend, tied to measurable results.</p><p>This shift forces a higher bar on product quality. If you price on outcomes, you need reliability, instrumentation, and attribution. You have to prove the agent drove a reduction in handle time, improved collections, decreased no-shows, or increased conversions. The vendors that can measure this cleanly will close faster and expand faster, because the ROI story is built into the contract.</p><p>We’ll also see hybrid models emerge: a base platform fee plus outcome upside, or per-workflow pricing where the unit is a completed task. The big idea is simple: when AI is an operator, not a tool, the pricing unit becomes work completed and value created.</p><h3>6. Multi-Agent Collaboration Becomes the New Org Chart</h3><p>In 2026, “multi-agent” stops being a buzzword and starts being the default architecture for real deployments. As soon as you move beyond simple tasks, you need separation of concerns: one agent to interpret intent, another to retrieve context, another to execute actions, another to verify and log. That’s an org chart — just implemented in software.</p><p>Multi-agent collaboration also unlocks better performance over time. When you separate roles, you can tune and evaluate each agent independently, swap components without breaking the whole system, and add new specialists as workflows expand. It’s a scalable way to build agentic products that don’t collapse under complexity.</p><p>The key is orchestration and observability. The coordinator agent needs to maintain state, track what’s pending, and enforce policies across agents. And every step needs to be traceable. The companies that get this right will scale agents across departments the same way strong orgs scale teams: with structure, accountability, and clear execution paths.</p><h3>7. Healthy MAUs Drives Preventative Care and Patient Engagement</h3><p>Healthcare has been optimized for “sick visits,” not continuous health. In 2026, that starts to change as we see the rise of Healthy MAUs: people who engage with healthcare monthly even when they aren’t acutely ill. The shift is subtle but massive — healthcare becomes a relationship, not an event.</p><p>AI makes this economically viable. Instead of relying on overwhelmed staff to check in, follow up, and nudge patients, AI can handle lightweight touchpoints at scale: reminders, education, post-visit follow ups, medication adherence, and proactive outreach. The result is more prevention, fewer missed appointments, and earlier detection of issues that would otherwise become expensive emergencies.</p><p>The winners will build trust and continuity. Patients don’t want more apps; they want care that feels personalized and consistent. Voice agents and messaging agents that can understand context, keep a timeline of the patient journey, and escalate to humans at the right moment will define the next generation of patient access and engagement.</p><h3>8. Building for Agents: The Next Wave of Infra</h3><p>We’ve spent decades building software for humans to click through. In 2026, more infrastructure will be built for agents to operate directly — clean APIs, structured data, tool interfaces, event-driven workflows, and systems that make it easy for agents to take actions safely and consistently. The shift isn’t just “more automation,” it’s a different kind of workload.</p><p>Agents run at agent-speed, not human-speed. Instead of a predictable 1:1 pattern (one user action → one system response), a single agentic goal can trigger a recursive fan-out of thousands of sub-tasks, queries, and internal API calls in seconds. To legacy databases, queues, and rate limiters, this can look less like a user and more like a thundering herd — sometimes indistinguishable from a DDoS if your backend isn’t built for bursty, parallel execution.</p><p>The winners will rebuild the control plane for this reality: higher concurrency by orders of magnitude, tighter latency variance, faster cold starts, and stronger coordination primitives (routing, locking, state management, retries, and policy enforcement). Building for agents isn’t just speed — it’s making agent execution safe, inspectable, and scalable when “massive parallel tool use” becomes the default.</p><h3>9. “Know Your Agent” Becomes a Mandate for Access and Audit</h3><p>As agents get real permissions, identity becomes unavoidable. In 2026, enterprises will treat agents like employees from an access standpoint: least privilege, clear scopes, approvals, and full logs of what the agent accessed and what it changed. If an agent can schedule, refund, update records, or trigger workflows, security teams will demand the same rigor they apply to human users.</p><p>This shifts the question from “what did the model say?” to “who authorized this agent, what was it allowed to do, and what exactly did it do?” That’s why access control and audit trails become core product features. Every action needs attribution, timestamps, context, and a replayable trail — especially in regulated industries like healthcare and finance.</p><p>Expect a wave of tooling around agent IAM: per-agent credentials, policy engines, sandboxing, anomaly detection, and kill switches that can revoke access instantly. The winners won’t just be the agents that perform well — they’ll be the ones that operate inside a framework of trust that enterprises can govern at scale.</p><h3>10. An AI Lab Goes Public</h3><p>The biggest AI milestone in 2026 might not be a model launch — it might be a filing. Frontier labs are committing to compute at a scale where private funding starts to feel like a bridge, not a destination. Public markets are ultimately the only capital pool deep enough to fund multi-year infrastructure ambitions without constantly re-opening the private round machine.</p><p>Anthropic feels like the most likely first mover. They’ve hired Wilson Sonsini to begin IPO preparations, and their growth curve is exactly the kind public markets understand: fast, enterprise-driven expansion. Anthropic has said it started 2025 around a $1B run-rate and crossed $5B+ by August, while reporting suggests it was nearing ~$7B in the fall, targeting ~$9B exiting 2025, with internal goals of $20B–$26B annualized revenue in 2026.</p><p>OpenAI is building toward the same horizon. Public reporting puts OpenAI around a $13B annualized run-rate with potential to reach ~$20B by year-end, and groundwork is already being laid for what a public-market story could look like. The punchline: an IPO would force a new level of discipline — GAAP scrutiny, quarterly expectations, and a market that cares about margins and durability as much as capability.</p><p>I’m incredibly excited about the year ahead. These predictions capture the trends and shifts I believe will shape AI in 2026, from the practical realities of deploying AI at scale to the new frontiers of agentic software and AI-driven healthcare. It’s such a fun time to be building, and I’m grateful to be doing it alongside so many ambitious founders, operators, and investors. Wishing everyone a great year ahead.</p><p>Cheers,<br>Aditya Bahl</p><p><strong>References</strong></p><ol><li><a href="https://sequoiacap.com/article/ai-in-2026-the-tale-of-two-ais/">https://sequoiacap.com/article/ai-in-2026-the-tale-of-two-ais/</a></li><li><a href="https://a16z.com/newsletter/big-ideas-2026-part-1/#agent-native-infrastructure-becomes-table-stakes">https://a16z.com/newsletter/big-ideas-2026-part-1/#agent-native-infrastructure-becomes-table-stakes</a></li><li><a href="https://a16z.com/newsletter/big-ideas-2026-part-2/">https://a16z.com/newsletter/big-ideas-2026-part-2/</a></li><li><a href="https://a16z.com/newsletter/big-ideas-2026-part-3/">https://a16z.com/newsletter/big-ideas-2026-part-3/</a></li><li><a href="https://hai.stanford.edu/news/stanford-ai-experts-predict-what-will-happen-in-2026">https://hai.stanford.edu/news/stanford-ai-experts-predict-what-will-happen-in-2026</a></li><li><a href="https://www.forbes.com/sites/robtoews/2025/12/22/10-ai-predictions-for-2026/">https://www.forbes.com/sites/robtoews/2025/12/22/10-ai-predictions-for-2026/</a></li><li><a href="https://www.linkedin.com/pulse/where-ai-headed-2026-ashu-garg-eyr2c/?trackingId=EykLkDaWSVO6in%2BQylbQhA%3D%3D">https://www.linkedin.com/pulse/where-ai-headed-2026-ashu-garg-eyr2c/?trackingId=EykLkDaWSVO6in%2BQylbQhA%3D%3D</a></li><li><a href="https://foundationcapital.com/context-graphs-ais-trillion-dollar-opportunity/">https://foundationcapital.com/context-graphs-ais-trillion-dollar-opportunity/</a></li><li><a href="https://foundationcapital.com/what-it-takes-to-build-ai-agents-that-actually-work/">https://foundationcapital.com/what-it-takes-to-build-ai-agents-that-actually-work/</a></li><li><a href="https://insights.euclid.vc/p/40-predictions-for-2026">https://insights.euclid.vc/p/40-predictions-for-2026</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2838703fa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aditya’s Top AI Predictions for 2025]]></title>
            <link>https://medium.com/@aditya.addy.bahl/adityas-top-ai-predictions-for-2025-f2f155ba2acb?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2f155ba2acb</guid>
            <category><![CDATA[openai-o3]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 16:33:59 GMT</pubDate>
            <atom:updated>2025-01-06T16:33:59.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lttCeEgtMogYBZ0zvLDrSg.png" /></figure><p>Happy New Year and Welcome to 2025! As we step into another exciting year, I’m filled with optimism for what lies ahead. In 2024, we witnessed a foundational shift — a primordial year for AI — marked by major investments and technological advancements that laid the groundwork for transformative change. Now, the focus turns to results. Organizations worldwide are poised to unlock the ROI of their AI investments and harness the full power of this game-changing technology. Here’s a glimpse at what I believe will define AI in 2025:</p><h3>1. The Year of AI Agents in Production</h3><p>In 2025, AI agents are set to revolutionize industries by acting as digital workers capable of handling not only repetitive tasks but also complex workflows that require advanced reasoning. These agents can autonomously manage intricate processes such as writing code, optimizing supply chains, and enhancing customer service operations. Their ability to collaborate in teams allows them to cross-verify outputs, ensuring higher accuracy and efficiency. Through reinforcement learning, these agents continuously improve their performance, adapting to new challenges and refining their decision-making capabilities.</p><p>The implications of deploying AI agents are profound across various sectors. In finance, for instance, AI agents can automate regulatory filings and streamline client interactions, reducing the workload on junior staff and allowing them to focus on higher-value tasks. In healthcare, AI agents can assist with clinical documentation and patient communications, enhancing operational efficiency and patient care. The advertising industry is also poised for transformation, with AI-generated content enabling brands to produce marketing materials more efficiently and cost-effectively. As these digital workers become integral to business operations, they are expected to drive significant productivity gains and innovation across the board.</p><h3>2. XAI’s 100k Cluster, Scaling Laws, and the Resurgence of Nuclear Energy</h3><p>In 2025, xAI’s construction of the Colossus supercomputer — featuring an unprecedented 100,000 NVIDIA H100 GPUs — has set a new benchmark in AI infrastructure. This cluster, the largest ever assembled, demonstrates xAI’s commitment to pushing the boundaries of what’s computationally possible. Leveraging scaling laws, xAI’s latest model, Grok 3, is expected to deliver groundbreaking performance, possibly surpassing existing large language models in capabilities like reasoning and code generation. Plans to expand Colossus to over one million GPUs highlight the escalating demand for compute power, emphasizing the critical need for sustainable energy solutions and advanced cooling technologies.</p><p>The resurgence of nuclear energy is emerging as a linchpin for powering AI’s insatiable computational appetite. With electricity consumption rising for the first time in decades, hyperscale data centers are turning to clean, reliable nuclear power. Decommissioned plants, such as Pennsylvania’s Three Mile Island, are being brought back online, reflecting bipartisan support for clean energy and significant capital investments. Beyond addressing energy needs, this nuclear renaissance ensures resilience in America’s aging grid while bolstering its leadership in the global AI race. By coupling nuclear energy with innovations like underwater data centers and diamond cooling, 2025 marks a pivotal year for both energy and AI infrastructure.</p><h3><strong>3. Better Reasoning Models: AI Unlocks New AI</strong></h3><p>OpenAI’s latest advancement, the o3 model, represents a significant leap in AI reasoning capabilities. Building upon the o1 series, o3 is designed to tackle complex problem-solving tasks with enhanced logical processing. It employs a “private chain of thought” mechanism, allowing the model to deliberate internally before generating responses, thereby improving accuracy in areas such as coding, mathematics, and scientific reasoning. Notably, o3 achieved a record-breaking score on the ARC-AGI benchmark, indicating performance comparable to human reasoning abilities.</p><p>In parallel, Sakana AI is pioneering the development of AI systems that autonomously drive scientific discovery. Their “AI Scientist” initiative leverages nature-inspired methods to create models capable of open-ended learning and experimentation. By automating the research process, these AI systems can generate new hypotheses, design experiments, and interpret results without human intervention. This approach not only accelerates the pace of innovation but also opens avenues for AI to contribute to fields traditionally dominated by human intellect, potentially leading to breakthroughs that were previously unimaginable.</p><h3><strong>4. GLP-1 and Breakthroughs in Medicine</strong></h3><p>In 2025, the integration of artificial intelligence (AI) in healthcare is set to revolutionize the development and application of GLP-1 receptor agonists, a class of drugs pivotal in treating metabolic disorders such as diabetes and obesity. AI-driven research accelerates drug discovery processes by analyzing complex datasets to identify novel therapeutic targets and optimize drug design. This technological synergy enhances the efficacy and safety profiles of GLP-1 therapies, expediting their journey from laboratory research to clinical application.</p><p>Moreover, AI’s capacity to process vast amounts of patient data facilitates the advancement of personalized medicine. By evaluating individual genetic profiles, lifestyle factors, and health records, AI algorithms can predict patient responses to GLP-1 treatments, enabling healthcare providers to tailor interventions that maximize therapeutic outcomes. This personalized approach not only improves patient care but also contributes to the broader field of precision medicine, where treatments are customized to the unique characteristics of each patient.</p><h3><strong>5. The Death of SaaS: Outcome-Based Pricing Models Take Over</strong></h3><p>In 2025, the traditional subscription-based Software as a Service (SaaS) model is undergoing a significant transformation, giving way to outcome-based pricing structures. This shift aligns costs directly with the tangible results delivered by AI solutions, ensuring that businesses pay for actual value received rather than mere access to software. Such models foster stronger vendor-client relationships, as both parties are mutually invested in achieving specific, measurable outcomes.</p><p>Industries where return on investment (ROI) is critical, such as marketing and healthcare, are at the forefront of adopting outcome-based pricing. For instance, marketing automation platforms may charge clients based on lead conversion rates or sales growth attributed to their tools, directly linking fees to performance. Similarly, in healthcare, AI-driven diagnostic systems might implement pricing tied to improvements in patient outcomes or operational efficiencies. This evolution in pricing strategy reflects a broader trend towards value-based engagements, where the emphasis is on delivering and paying for concrete business results.</p><h3><strong>6. AI-Driven Automation in Manufacturing</strong></h3><p>In 2025, the convergence of artificial intelligence (AI) and robotics is set to revolutionize manufacturing processes, ushering in an era of unprecedented automation and efficiency. Leading companies like Foxconn are at the forefront of this transformation, leveraging AI to enhance production capabilities. Foxconn’s collaboration with NVIDIA to develop ‘AI factories’ exemplifies this trend, aiming to digitalize manufacturing workflows and integrate AI-powered robotics into assembly lines. This partnership focuses on creating data centers that support applications such as electric vehicle development and smart manufacturing, highlighting the pivotal role of AI in modern industrial operations.</p><p>Similarly, Tesla’s integration of AI into its manufacturing processes underscores the industry’s shift towards intelligent automation. By utilizing AI for production planning, quality control, and the development of autonomous systems, Tesla enhances operational efficiency and product innovation. This strategic adoption of AI not only streamlines manufacturing but also positions Tesla at the forefront of automotive innovation, demonstrating the transformative potential of AI-driven automation in hardware-centric industries.</p><h3><strong>7. Mainstream Adoption of Real-Time Voice AI</strong></h3><p>In 2025, real-time voice AI is poised to become an integral part of daily life, enabling users to interact with technology through natural, conversational speech. This evolution is driven by significant advancements in natural language processing and machine learning, resulting in AI assistants that understand and respond to human speech with remarkable accuracy. The integration of voice AI into various devices and applications enhances productivity tools, customer service interactions, and personal companionship, bringing us closer to truly intelligent assistants.</p><p>Industries are rapidly adopting voice AI to improve user experiences and operational efficiency. In healthcare, AI-powered voice assistants are assisting physicians by automating medical note-taking, allowing doctors to focus more on patient care. In the automotive sector, collaborations like the one between Cerence AI and NVIDIA are enhancing in-car voice recognition systems, providing drivers with seamless, hands-free control over vehicle functions. These developments indicate a broader trend towards voice-first interactions, where speaking to devices becomes as commonplace as typing or touching, fundamentally transforming how we engage with technology.</p><h3><strong>8. Enterprises Embrace Stablecoins for Payments</strong></h3><p>In 2025, stablecoins have solidified their position as the most cost-effective method for dollar-denominated transactions, facilitating rapid global payments without the constraints of traditional banking systems. This efficiency has led to their widespread adoption among small and medium-sized businesses (SMBs), particularly in sectors like retail and hospitality, where transaction fees significantly impact profit margins. For instance, a coffee shop can save approximately 2–3% per transaction by accepting stablecoins instead of credit cards, directly enhancing their bottom line.</p><p>As SMBs experience these benefits, larger enterprises are beginning to recognize the substantial cost savings and operational efficiencies offered by stablecoin adoption. By integrating stablecoins into their payment infrastructures, these companies can bypass traditional payment processors, reducing fees and accelerating transaction times. This shift not only improves financial performance but also encourages the development of new solutions for challenges such as fraud protection and identity verification, traditionally managed by credit card companies. The growing interest from major financial institutions further underscores the potential of stablecoins to revolutionize enterprise payment systems.</p><h3>9. Redefining Systems of Record with AI</h3><p>In 2025, artificial intelligence (AI) is prompting enterprises to reevaluate their foundational technology infrastructures. A notable example is Klarna’s decision to replace traditional platforms like Salesforce and Workday with custom-built AI solutions, aiming to streamline operations and reduce costs. This move reflects a broader trend where businesses are moving away from legacy systems of record in favor of dynamic, AI-driven platforms that offer enhanced flexibility and efficiency.</p><p>These AI-powered systems, often referred to as “systems of engagement,” not only store essential data but also serve as interactive platforms that automate tasks, transforming human roles from active participants to supervisory reviewers. By integrating AI, these systems can manage and interpret data in real-time, providing actionable insights that support informed decision-making. While transitioning to such advanced systems presents challenges, including overcoming the entrenched positions of established providers, the potential benefits make this an attractive pursuit for forward-thinking enterprises.</p><h3>10. The Decline of Traditional Search Engines</h3><p>In 2025, the dominance of traditional search engines, particularly Google — which has historically controlled about 90% of the U.S. search market — is facing unprecedented challenges. A recent U.S. antitrust ruling has prompted device manufacturers like Apple to consider empowering alternative search providers, potentially disrupting Google’s longstanding agreements. Concurrently, the rise of generative AI technologies is reshaping user interactions with search platforms. Tools such as ChatGPT, boasting over 250 million weekly active users, and answer engines like Perplexity, which is experiencing monthly growth exceeding 25%, are attracting users with their ability to provide concise, context-rich responses. Notably, user engagement patterns are evolving; queries on these platforms average around 10 words — more than triple the length of traditional search queries — and nearly half lead to follow-up questions, indicating a shift towards more in-depth information retrieval.</p><p>This transformation is further evidenced by the increasing reliance on AI-driven, domain-specific search tools. Professionals are turning to platforms like Causaly for scientific research, Consensus for academic studies, Harvey for legal inquiries, and Hebbia for financial services, seeking precise and context-aware information tailored to their specific needs. Traditional search engines, cluttered with ads and links, often require users to sift through results, diminishing the efficiency of information retrieval. In contrast, AI-powered platforms deliver direct answers and deeper insights, aligning with user preferences for streamlined and effective search experiences. As a result, the longstanding dominance of traditional search engines is being challenged, signaling a significant shift in the digital information landscape.</p><h3>11. Surge in AI-Related Mergers and Acquisitions</h3><p>In 2025, the artificial intelligence (AI) sector is experiencing a significant increase in mergers and acquisitions (M&amp;A), driven by a favorable political climate and the strategic imperative for companies to enhance their technological capabilities. The incoming administration’s deregulatory stance towards technology and AI has created an environment conducive to corporate consolidations. This shift is expected to facilitate a wave of M&amp;A activity, enabling companies to integrate advanced AI technologies and maintain a competitive edge in the rapidly evolving market.</p><p>This surge in M&amp;A is reshaping the AI industry, fostering collaborations between startups and established corporations to accelerate innovation and expand market reach. The increased investment in AI-driven solutions is not only transforming business operations but also contributing to economic growth. As companies navigate this dynamic landscape, strategic acquisitions are becoming essential for those aiming to lead in the AI revolution.</p><p>Wishing everyone a great year!</p><p>Cheers,</p><p><strong>Aditya Bahl</strong></p><p><strong>CEO of Buildnow.ai</strong></p><p><strong>References</strong></p><ol><li><a href="https://nbt.substack.com/p/nextbigthing2025">https://nbt.substack.com/p/nextbigthing2025</a></li><li><a href="https://hai.stanford.edu/news/predictions-ai-2025-collaborative-agents-ai-skepticism-and-new-risks">https://hai.stanford.edu/news/predictions-ai-2025-collaborative-agents-ai-skepticism-and-new-risks</a></li><li><a href="https://www.sequoiacap.com/article/ai-in-2025/">https://www.sequoiacap.com/article/ai-in-2025/</a></li><li><a href="https://a16z.com/big-ideas-in-tech-2025/">https://a16z.com/big-ideas-in-tech-2025/</a></li><li><a href="https://www.thetimes.com/business-money/companies/article/2025-is-the-year-ai-will-upend-advertising-im-going-to-make-sure-it-does-6vbkhxp2f?utm_source=chatgpt.com&amp;region=global">https://www.thetimes.com/business-money/companies/article/2025-is-the-year-ai-will-upend-advertising-im-going-to-make-sure-it-does-6vbkhxp2f?utm_source=chatgpt.com&amp;region=global</a></li><li><a href="https://www.fnlondon.com/articles/investment-banks-look-to-2025-ai-push-to-remove-junior-drudge-work-8dfc606c?utm_source=chatgpt.com">https://www.fnlondon.com/articles/investment-banks-look-to-2025-ai-push-to-remove-junior-drudge-work-8dfc606c?utm_source=chatgpt.com</a></li><li><a href="https://techcrunch.com/2024/12/20/openai-announces-new-o3-model/?utm_source=chatgpt.com">https://techcrunch.com/2024/12/20/openai-announces-new-o3-model/?utm_source=chatgpt.com</a></li><li><a href="https://www.wired.com/story/ai-scientist-ubc-lab/?utm_source=chatgpt.com">https://www.wired.com/story/ai-scientist-ubc-lab/?utm_source=chatgpt.com</a></li><li><a href="https://www.drugdiscoverytrends.com/glp-1s-adcs-ai-and-the-future-of-pharma/?utm_source=chatgpt.com">https://www.drugdiscoverytrends.com/glp-1s-adcs-ai-and-the-future-of-pharma/?utm_source=chatgpt.com</a></li><li><a href="https://www.lek.com/insights/tmt/us/ei/rise-outcome-based-pricing-saas-aligning-value-cost?utm_source=chatgpt.com">https://www.lek.com/insights/tmt/us/ei/rise-outcome-based-pricing-saas-aligning-value-cost?utm_source=chatgpt.com</a></li><li><a href="https://investor.nvidia.com/news/press-release-details/2023/NVIDIA-Partners-With-Foxconn-to-Build-Factories-and-Systemsfor-the-AI-Industrial-Revolution/default.aspx?utm_source=chatgpt.com">https://investor.nvidia.com/news/press-release-details/2023/NVIDIA-Partners-With-Foxconn-to-Build-Factories-and-Systemsfor-the-AI-Industrial-Revolution/default.aspx?utm_source=chatgpt.com</a></li><li><a href="https://www.ft.com/content/5c356658-6db4-47c1-940b-b2e3cf3a51f3?utm_source=chatgpt.com">https://www.ft.com/content/5c356658-6db4-47c1-940b-b2e3cf3a51f3?utm_source=chatgpt.com</a></li><li><a href="https://www.newsbtc.com/news/crypto-predictions-2025-dragonfly-managing-partner/?utm_source=chatgpt.com">https://www.newsbtc.com/news/crypto-predictions-2025-dragonfly-managing-partner/?utm_source=chatgpt.com</a></li><li><a href="https://www.inc.com/sam-blum/klarna-plans-to-shut-down-saas-providers-and-replace-them-with-ai.html?utm_source=chatgpt.com">https://www.inc.com/sam-blum/klarna-plans-to-shut-down-saas-providers-and-replace-them-with-ai.html?utm_source=chatgpt.com</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2f155ba2acb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Empathy? Its Role in AI Adoption]]></title>
            <link>https://medium.com/@aditya.addy.bahl/what-is-empathy-its-role-in-ai-adoption-3cb286c9fbfe?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb286c9fbfe</guid>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 20:00:05 GMT</pubDate>
            <atom:updated>2024-07-10T20:16:08.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yA1KVL08YypAK0xcCTtWHA.jpeg" /><figcaption>Emotions From Movie Inside Out 2</figcaption></figure><p>Apple’s Siri came out in 2011, and Amazon’s Alexa followed in 2014, bringing the promise of AI voice assistants into our lives. By 2024, while the adoption of these assistants has increased, it has not reached its full potential. One might wonder why. The primary reason is the perception that AI assistants don’t understand us and can’t follow our instructions. Although we’ve moved away from a rules-based approach, and thanks to Large Language Models (LLMs), AI can now provide better, more personalized responses. However, correct and accurate responses alone aren’t enough; these AI assistants need to be more empathetic.</p><h3>Understanding Empathy</h3><p>Empathy is the ability to understand and share the feelings of another. It’s the cornerstone of human interaction, fostering connection and communication. For instance, consider a friend who knows when to offer support or simply listen; that’s empathy in action. In the context of AI, empathy doesn’t mean machines feel emotions like humans do. Instead, it refers to the AI’s ability to recognize human emotions, understand context, and respond in ways that are considerate and appropriate.</p><p>For AI to be truly useful and integrated into our daily lives, it needs to exhibit a form of empathy. This doesn’t just make interactions more pleasant but also builds trust and improves user satisfaction. When users feel understood, they are more likely to continue using and relying on the technology.</p><h3>Semantic Space Theory</h3><p>To develop empathetic AI, we need to delve into Semantic Space Theory. This theory, as discussed by Hume AI, involves a data-driven, computational approach to understanding emotions. It maps the full spectrum of human feelings, moving beyond the traditional six categories of anger, disgust, fear, happiness, sadness, and surprise, and viewing emotion as a high-dimensional semantic space.</p><h4>Key Takeaways:</h4><ol><li><strong>Emotion is High-Dimensional:</strong></li></ol><ul><li>A range of emotions, mental states, and nonverbal behaviors are collected.</li><li>Techniques map semantic spaces in self-reported experience, facial expressions, speech prosody, vocal bursts, music, and even ancient art.</li><li>Researchers have identified 20 distinct dimensions of emotion.</li></ul><p><strong>2. Emotion Categories Are Not Discrete:</strong></p><ul><li>Emotions blend and overlap in a continuous semantic space, rather than fitting into rigid categories.</li></ul><p><strong>3. Specific Emotions Organize Behavior:</strong></p><ul><li>Emotions are real and organize emotional behavior effectively, influencing how we react and interact.</li></ul><p>Semantic Space Theory helps in categorizing and understanding the vast range of human emotions in a structured manner. By applying this theory, AI can better grasp the nuances of human emotions, leading to more accurate and empathetic responses. This capability is crucial for creating AI that can engage in meaningful, human-like interactions.</p><h3>The Benefits of Nailing Empathy in AI</h3><ol><li><strong>Customer Service</strong></li></ol><ul><li>Imagine AI customer service representatives who can not only solve problems but also comfort and reassure frustrated customers. This would lead to higher customer satisfaction and loyalty. For instance, an empathetic AI could detect frustration in a customer’s voice and respond with a calming and understanding tone, offering solutions tailored to their needs.</li></ul><p><strong>2. Education</strong></p><ul><li>In education, empathetic AI tutors could provide personalized support to students, understanding their emotional states and adjusting their teaching methods accordingly. This could make learning more engaging and effective, particularly for students who may struggle with traditional educational methods. An AI tutor might notice a student’s confusion and offer a different explanation or additional practice problems.</li></ul><p><strong>3. Healthcare</strong></p><ul><li>Empathetic AI can play a significant role in healthcare. AI that understands and responds to patient emotions can improve patient care, making interactions more supportive and less clinical. This would be particularly beneficial in mental health services, where understanding and empathy are critical. For example, an AI therapist could provide responses that validate a patient’s feelings, creating a sense of connection and support.</li></ul><p><strong>4. New Markets and Use Cases</strong></p><ul><li>Empathy in AI also opens up new markets and use cases. AI companions for the elderly could provide not just assistance but also emotional support, reducing feelings of loneliness and isolation. In the corporate world, empathetic AI can enhance team collaboration by recognizing and addressing interpersonal dynamics and conflicts. An AI team member might mediate a disagreement by acknowledging each person’s perspective and suggesting a compromise.</li></ul><h3>Conclusion</h3><p>Empathy is not just a nice-to-have feature for AI; it is a necessity for widespread adoption and meaningful integration into our lives. By understanding and implementing Semantic Space Theory, we can develop AI that doesn’t just respond correctly but does so with a human touch. This will unlock new possibilities and use cases, creating a future where AI is not just smart but also compassionate.</p><p>As we move forward, the challenge lies in ensuring that our AI systems are equipped with the tools to understand and respond to human emotions accurately. By doing so, we can create a new era of empathetic AI, transforming our interactions with technology and opening up a world of opportunities. Let’s strive to build AI that understands us, not just answers us.</p><h3>References:</h3><ol><li><a href="https://www.hume.ai/blog/what-is-semantic-space-theory">https://www.hume.ai/blog/what-is-semantic-space-theory</a></li><li><a href="https://www.hume.ai/blog/introducing-hume-evi-api">https://www.hume.ai/blog/introducing-hume-evi-api</a></li><li><a href="https://www.psychologytoday.com/us/basics/empathy">https://www.psychologytoday.com/us/basics/empathy</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb286c9fbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Addy’s Top AI Predictions for 2024]]></title>
            <link>https://medium.com/@aditya.addy.bahl/addys-top-ai-predictions-for-2024-46e869f68c69?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e869f68c69</guid>
            <category><![CDATA[enterprise]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[vertical-saas]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 19:52:54 GMT</pubDate>
            <atom:updated>2024-01-08T19:52:54.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taumLeK-wN9zqIS5KlpkcQ.png" /></figure><p>Happy New Year! 💙 As we bid farewell to 2023, a year that marked a turning point in AI’s global recognition, we usher in 2024 with even higher expectations. This year is set to be monumental for AI, as we anticipate enterprises deploying AI solutions on a larger scale, fundamentally boosting both profitability and productivity. So, let’s dive into the developments and ideas in AI that are capturing my attention and fueling my excitement for the year ahead:</p><ol><li><strong>4 Billion Voters at the Polls: The Critical Need for AI Regulation in the Age of Deepfakes — Is Democracy on the Line?</strong></li></ol><p>As we approach a pivotal election year with 4 billion people set to vote in 50 countries, the imperative for stringent AI regulation becomes increasingly evident, particularly in the era of deepfakes. The ease of digital content creation today, coupled with the expected surge in disinformation campaigns, poses a significant threat to the integrity of democratic processes. The proliferation of AI-manipulated content — from images to voice recordings and videos — risks undermining the authenticity of political discourse and the public’s trust in democratic institutions.</p><p>To counter these challenges, it’s essential to establish clear, actionable AI legislation, developed collaboratively by a diverse set of stakeholders, including governments, tech companies, civil society, and international bodies. Drawing on past experiences where the lack of AI regulation impacted democratic processes, these regulations should not only set standards for the transparency and accuracy of AI-generated content but also define ethical boundaries and penalties for misuse. Public education and awareness about the impacts of AI in information dissemination are crucial in this context, ensuring a well-informed electorate capable of discerning AI-influenced content.</p><p>Looking ahead, the goal of AI regulation in the democratic context is not merely preventative but also transformative. Properly regulated AI has the potential to enhance democratic participation, broaden access to information, and strengthen civic engagement. Frameworks like the EU AI Act, which offer a more structured approach than earlier initiatives such as the Biden executive order, can serve as benchmarks. The focus must be on developing regulations that ensure AI’s role in democracy is both ethically responsible and transparent, fostering an environment where AI not only protects but also enriches the democratic process.</p><p><strong>2. Multi-Modal will become a ubiquitous term</strong></p><p>In 2024, the implications of multi-modal AI models extend into diverse realms, including marketing and the entertainment industry, particularly in Hollywood. In the world of marketing, these advanced systems are set to revolutionize how brands interact with their audiences. Multi-modal AI can analyze and synthesize data from text, images, and audio to create highly personalized marketing campaigns. This technology enables marketers to craft messages that resonate deeply with individual consumer preferences and behaviors, leading to more effective and engaging advertising strategies.</p><p>Hollywood, too, stands on the brink of a transformation with the advent of multi-modal AI. This technology can be used to analyze scripts, predict audience responses, and even assist in the creative process of filmmaking. From enhancing visual effects to providing insights into viewer engagement, multi-modal AI opens up new avenues for storytelling and production. It can also streamline post-production processes by synchronizing audio and visual elements more efficiently. By integrating multiple forms of data analysis and interpretation, multi-modal AI is poised to become an invaluable tool in both marketing and Hollywood, pushing the boundaries of what’s possible in both creative expression and audience engagement.</p><p><strong>3. Big Year for AI Agents for Specific Workflows (I’m most excited about!)</strong></p><p>It’s not just about individual AI agents efficiently tackling specific tasks anymore. We’re gearing up for a transformative leap where these agents, each a specialist in its field, begin to interact and collaborate, forming an interconnected network. This goes beyond your AI assistant managing emails or handling customer queries. It’s about crafting an ecosystem where, for example, your personal AI shopper communicates seamlessly with a logistics agent to perfect your grocery delivery experience. This shift is monumental, signaling a new era in how we deploy and interact with AI technologies in our everyday lives.</p><p>In this emerging landscape, industry giants like Bloomberg in finance and LexisNexis in legal are poised to take the lead. They’re not merely repositories of vast domain-specific data; they’re at the forefront of deploying specialized AI agents. Imagine Bloomberg unleashing sophisticated finance-focused agents, leveraging their deep financial data wells, or LexisNexis deploying cutting-edge legal agents, drawing from their extensive legal information troves. These agents are set to transcend their roles as mere tools for end-users, evolving into integral components of a broader, more dynamic digital workforce. This evolution promises a future where AI agents don’t just perform tasks in isolation but collaborate, communicate, and make decisions in a manner reminiscent of human interaction. It’s an exhilarating prospect, marking the dawn of a new digital epoch. The realm of digital robotic process automation and the advancements in humanoid technology for tasks like manufacturing are about to take center stage in this new, interconnected AI universe.</p><p><strong>4. Voice-First AI Apps Revolutionize Productivity and Companionship</strong></p><p>In 2024, we’re set to witness a significant breakthrough in AI, particularly in the realm of voice-first applications, with a focus on companionship and productivity. Voice, despite being the most natural and ancient form of human communication, has long struggled to find its footing as a reliable interface for technology interaction. Earlier, even the likes of Satya Nadella of Microsoft acknowledged the limitations of voice assistants, including their own Cortana, labeling them as less than intelligent. Typically, our interaction with smart speakers has been confined to basic tasks like playing music or checking the weather, rather than extracting substantial value from voice-based interactivity. However, the landscape is changing dramatically, thanks to large language models that have propelled virtual assistants to near-human conversational abilities.</p><p>What’s particularly intriguing about voice as a modality is its distinct nature, which means that traditional apps aren’t inherently equipped to harness this form of interaction effectively. While we can anticipate AI-driven features being integrated into platforms like Gmail, it’s less probable that we’ll see Gmail adopt a fully-fledged AI voice interface within its inbox. The year 2024, in my view, will mark a pivotal moment where voice applications not only become more functional but also more seamlessly woven into the fabric of our daily lives.</p><p><strong>5. Healthcare is beyond broken, spent the first two days of the year in the ER, plz fix NOW!</strong></p><p>The beginning of the year was quite unexpected, as I found myself spending the first two days in a hospital in Hollywood, California, offering support to a friend. It was shocking to witness the state of our healthcare system from the inside. Despite appearing well-structured from the outside, the reality within the emergency department raised several concerns. In a country like the United States, a seven-hour wait to see a doctor in the emergency room is unacceptable. Those who come to the emergency room are clearly in distress and need prompt attention. Observing the situation closely, it became apparent that a critical issue was the lack of sufficient medical staff. This experience led me to ponder over potential AI solutions, like AI companions in emergency rooms to assist patients. Often, a doctor’s brief visit can leave patients anxious and confused during long waiting periods. A virtual nurse in each emergency room could provide real-time information to patients about their condition and vitals. Another significant issue I noticed was the inefficiency in administrative tasks, such as form filling, which took hours and prolonged patient wait times. Automating these administrative processes in healthcare seems like a massive opportunity for improvement.</p><p>From seamless integration of ambient note-taking within electronic health records to the intelligent automation of triage systems, and precision in treatment planning, AI has the potential to significantly reduce the administrative load and burnout among physicians. This advancement is crucial for optimizing the care we provide, ensuring it’s not only the highest quality but also deeply empathetic. Looking ahead, I envision AI-enabled platforms playing a pivotal role in advancing value-based care. Despite its current underperformance, AI’s ability to enable providers could be the catalyst that elevates value-based care to its full potential, ultimately benefiting both healthcare professionals and patients alike.</p><p><strong>6. NVIDIA will move upstream and seek to become a cloud provider</strong></p><p>In the dynamic landscape of AI and technology, most organizations don’t directly purchase GPUs from Nvidia but access them through cloud services like Amazon Web Services, Microsoft Azure, and Google Cloud Platform. These cloud giants, which are Nvidia’s major customers, are evolving into its competitors. As the value of AI increasingly aligns with the capabilities of the silicon layer, evident from Nvidia’s soaring stock price, these cloud providers are investing in developing their own AI chips. This move positions them in direct competition with Nvidia’s GPUs. Witnessing this shift, Nvidia is strategically repositioning itself, potentially moving towards offering its own cloud services and operating data centers, thereby reducing its dependency on these cloud companies for distribution. Nvidia’s foray into this new domain began with the launch of DGX Cloud, and we anticipate a significant expansion of this strategy in the coming year. This expansion might include setting up their own data centers, currently hosted within other providers’ infrastructures, or even acquiring a cloud provider like CoreWeave, a close partner. As we head into 2024, the relationship between Nvidia and these leading cloud providers is set to become increasingly intricate and competitive.</p><p><strong>7. Stability AI’s Impending Shutdown: A Legacy in Open Source, Hindered by Business Model Challenges</strong></p><p>Stability AI, once a rising star in the AI industry, has been struggling throughout 2023, no longer able to maintain its earlier momentum. The company has been facing a significant talent drain, with key positions like the chief operating officer, chief people officer, and various vice presidents across engineering, product, machine learning, communications, research, audio, and legal departments exiting the firm. Notably, both Coatue and Lightspeed, the leading investors in Stability’s $100 million funding round last year, have reportedly stepped down from the company’s board following disagreements with CEO Emad Mostaque. Efforts to secure additional funding at a $4 billion valuation earlier this year were unsuccessful.</p><p>Looking ahead to next year, it seems increasingly likely that Stability AI may succumb to these challenges and cease operations. Despite attempts to find a buyer, the startup has attracted little interest. However, a recent $50 million investment from Intel has given Stability a temporary lifeline. This move by Intel appears driven by a strategic intent to showcase a major client for its new AI chips, as it competes with Nvidia. But, the concern remains: Stability’s high expenditure rate — reportedly $8 million per month against much lower revenues — suggests that even with Intel’s investment, the company’s financial runway might not extend beyond the end of 2024.</p><p><strong>8. A new framework distinct from the transformer architecture will start to be widely adopted.</strong></p><p>The transformer architecture, a groundbreaking innovation from Google in 2017, has become the bedrock of contemporary AI technology. It’s what powers the engines of today’s most prominent AI models and products like ChatGPT, Midjourney, and GitHub Copilot. But in the ever-evolving landscape of AI, no single technology remains unchallenged indefinitely. Currently, at the fringes of AI research, there’s a stirring of innovation, with several groups dedicating their efforts to develop next-gen AI architectures. These new models aim to surpass transformers in various capacities, marking a potential shift in AI’s trajectory.</p><p>Among these pioneering efforts is Chris Ré’s lab at Stanford, a hub of groundbreaking work in AI architecture. The team’s primary goal is to devise a model that scales sub-quadratically with sequence length, a leap forward from the quadratic scaling of transformers. This advancement promises AI models that are less taxing computationally and more adept at handling longer sequences. Notable architectures emerging from Ré’s lab, such as S4, Monarch Mixer, and Hyena, are already making waves. The latest, Mamba, has sparked significant excitement, being heralded by some as a potential successor to transformers. Parallel to these academic pursuits, initiatives like MIT’s liquid neural networks and startups like Sakana AI are also exploring alternatives to the transformer paradigm. Looking towards 2024, I foresee these novel architectures transitioning from research curiosities to viable, widely-adopted alternatives in real-world AI applications. While transformers won’t vanish overnight — given their deep integration in critical AI systems — the coming year could well be a turning point, ushering in a new era of diverse, advanced AI architectural options.</p><p><strong>9. Year Of The AI Wearables &amp; XR</strong></p><p>As we step into 2024, we’re at the cusp of a revolution in our interaction with technology, driven by the fusion of AI, wearables, and extended reality (XR) devices. This isn’t just a technological leap; it’s a shift in how we perceive and integrate technology into our daily lives. These devices are evolving from simple gadgets to become extensions of our digital selves, blending into our routines with an ease that was previously unimaginable. Leading this transformative trend are innovative products like Humane AI’s Pin and Tab, powered by Qualcomm Snapdragon processors. These wearables redefine the landscape, transcending traditional roles of health tracking and notifications to enhance human interactions, provide AI-assisted real-time insights, and augment our perception of the surrounding world.</p><p>Another groundbreaking innovation is Rewind, which is reimagining our approach to capturing and reliving memories. Imagine a device that not only records life’s moments but also enables a deeper engagement with our past experiences. This wave of innovation isn’t limited to newcomers; tech heavyweights like Apple and OpenAI are also making their foray into the wearable domain. Apple, with its history of creating iconic devices, is likely to introduce wearables that flawlessly mesh with its ecosystem, particularly the XR Apple Vision Pro, promising an unparalleled user experience. OpenAI, leveraging its mastery in AI, could introduce wearables that integrate sophisticated AI functionalities, offering interactions with generative AI models like ChatGPT. Furthermore, Meta’s advances in VR wearables hint at the potential for immersive experiences that go beyond augmenting reality to creating new digital realms. As we progress through 2024, AI wearables are set to evolve beyond their roles as mere technological tools, transforming into personal companions, digital assistants, and portals to uncharted realities. This marks a transition towards a more intimate, interactive relationship with technology, where the lines between our digital and physical worlds are increasingly seamless.</p><p><strong>10. Emphasis on Vertical SaaS, Leaner teams, and Getting to profitability</strong></p><p>In 2024, AI startups are increasingly focusing on Vertical Software as a Service (SaaS) models, leaner team structures, and the crucial goal of achieving profitability. This shift in strategy comes as the industry recognizes the importance of specialized, sector-specific solutions over generic offerings. Vertical SaaS models allow AI startups to offer tailored, high-value services to niche markets, addressing specific industry needs with greater precision. This targeted approach not only enhances customer satisfaction but also boosts the potential for sustainable revenue streams. Additionally, the trend towards leaner teams is gaining momentum. Startups are now streamlining their operations, focusing on core competencies and reducing overheads. This lean approach maximizes efficiency and agility, enabling these companies to adapt quickly to market changes and customer demands, which is essential in the fast-paced AI landscape.</p><p>The drive towards profitability has never been more critical for AI startups. In an increasingly competitive market, simply securing funding or achieving high valuations is no longer enough. Investors are looking for startups that can demonstrate a clear path to profitability and sustainable growth. Those unable to move beyond burn rates and grow into their valuations face a stark reality: they risk running out of runway and becoming unsustainable. This pressure is reshaping how AI startups operate, compelling them to focus on revenue-generating activities and efficient business models. The startups that succeed in this environment will be those that not only innovate in AI technology but also excel in business acumen, striking a balance between cutting-edge technology and sound financial management. This focus on profitability, coupled with the adoption of Vertical SaaS and leaner structures, is setting a new benchmark for success in the AI startup ecosystem.</p><p>Let’s Bahl, much love! 🪩</p><p>Aditya Bahl 💙</p><p><strong>References</strong></p><ol><li><a href="https://cs.stanford.edu/~chrismre/">https://cs.stanford.edu/~chrismre/</a></li><li><a href="https://techcrunch.com/2023/08/17/what-is-a-liquid-neural-network-really/">https://techcrunch.com/2023/08/17/what-is-a-liquid-neural-network-really/</a></li><li><a href="https://a16z.com/big-ideas-in-tech-2024/">https://a16z.com/big-ideas-in-tech-2024/</a></li><li><a href="https://www.turingpost.com/p/fod33">https://www.turingpost.com/p/fod33</a></li><li><a href="https://towardsdatascience.com/navigating-the-ai-landscape-of-2024-trends-predictions-and-possibilities-41e0ac83d68f#4bee">https://towardsdatascience.com/navigating-the-ai-landscape-of-2024-trends-predictions-and-possibilities-41e0ac83d68f#4bee</a></li><li><a href="https://www.forbes.com/sites/robtoews/2023/12/21/10-ai-predictions-for-2024/?sh=2d05ad5b4898">https://www.forbes.com/sites/robtoews/2023/12/21/10-ai-predictions-for-2024/?sh=2d05ad5b4898</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e869f68c69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Democratizing AI! Fine-Tuning LLaMA 2: A Step-by-Step Instructional Guide]]></title>
            <link>https://medium.com/@aditya.addy.bahl/democratizing-ai-fine-tuning-llama-2-a-step-by-step-instructional-guide-19d3dad84202?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d3dad84202</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[democratizing-ai]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llama-2]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 22:25:36 GMT</pubDate>
            <atom:updated>2023-12-13T22:25:36.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6jTfzXeX75jPRJQ0L2usQ.png" /><figcaption>🦙</figcaption></figure><p>Many might consider ChatGPT the definitive AI story of 2023, but is that an accurate assessment? Credit must be given where it’s due: OpenAI’s ChatGPT has been recognized as the fastest-growing consumer app ever, amassing 100 million monthly users in just two months. It’s ChatGPT that catapulted Generative AI into the mainstream, igniting widespread interest in generative AI technologies. For context, it took Facebook four years to reach the same number of monthly users. While some advocate for a ‘slow and steady’ approach, might a ‘Llama’ 🦙 be the dark horse in this race?</p><p>Earlier this year, Meta released the first iteration of LLaMA in February, followed by the commercial LLaMA 2 in July. As the first major open-source large language model (LLM), LLaMA has fostered a burgeoning open ecosystem. Meta reports that the open-source community has fine-tuned and released over 7,000 LLaMA derivatives on Hugging Face. This democratization is pivotal, as previously only well-resourced companies and research institutions could afford to fine-tune or train such models.</p><p><strong>The LLaMA models are designed to address this gap, offering a commercial license to broaden accessibility. Innovations now enable fine-tuning on consumer GPUs with limited memory, further democratizing AI.</strong> By removing barriers to access, even smaller businesses can create bespoke models suited to their unique needs and budget constraints.</p><p>In this tutorial, we will delve into LLaMA 2, guiding you through each step to fine-tune it on your custom dataset. But first, let’s clarify some essential terminology to lay the groundwork for what’s to come.</p><h4><strong>What is Fine-Tuning? PEFT? LoRA? QLoRA?</strong></h4><p>Fine-tuning every parameter across all layers of a model certainly delivers impressive results, but it’s also a major resource hog. It demands a hefty amount of GPU power and a fair bit of time.</p><p>That’s where <strong>PEFT</strong>, or Parameter Efficient Fine Tuning, enters the picture. This approach is far <strong>more economical in terms of resources and costs.</strong> Two key methods under PEFT are <strong>LoRA</strong> (Low Rank Adaptation) and its more efficient variant, <strong>QLoRA</strong> (Quantized LoRA). These methods involve <strong>loading pre-trained models with quantized 8-bit and 4-bit weights onto the GPU. </strong>Interestingly, it’s quite feasible to fine-tune the Llama 2–13B model using LoRA or QLoRA on a standard 24GB consumer GPU. Notably, QLoRA is even more efficient, requiring less GPU memory and shortening fine-tuning time compared to LoRA.</p><p>The smart move is usually to start with LoRA or QLoRA (if resources are really tight), and then assess the performance. Full-scale fine-tuning should only come into play if these initial results aren’t up to par.</p><p><strong>What is quantization?</strong></p><p><strong>Quantization is a method where you convert those hefty 32-bit floating-point model weights into more compact formats like 16-bit floats, 16-bit ints, or even down to 8, 4, 3, or 2-bit ints.</strong> This nifty trick shrinks the model’s size, speeds up both fine-tuning and inference. It’s super crucial when you’re working in environments with limited resources, like on a single GPU, a Mac, or mobile devices (like what you see over at [<a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/llama.cpp</a>]). Without quantization, tuning the model or running inference in these scenarios would be a tough nut to crack. If you’re looking to dive deeper into quantization, there’s more info to check out <a href="https://pytorch.org/blog/introduction-to-quantization-on-pytorch/">here</a> &amp; <a href="https://huggingface.co/docs/optimum/concept_guides/quantization">here</a>.</p><p><strong>Fine-Tuning LLaMA 2: A Step-by-Step Instructional Guide</strong></p><ol><li><strong>Getting Started: Setting Up Your Environment</strong></li></ol><p>Let’s begin by setting up our environment. This involves installing the necessary libraries and importing the required modules to ensure a smooth fine-tuning process with LLaMA 2.</p><p>For this tutorial, I utilized a V100 High-RAM GPU, which provided robust performance for running the Google Colab notebook alongside the LLaMA 2 -7B-chat model. Below are the commands to install the essential libraries:</p><pre>!pip install -q accelerate==0.21.0 peft==0.4.0 bitsandbytes==0.40.2 transformers==4.31.0 trl==0.4.7 --progress-bar off</pre><pre>import json<br>import re<br>from pprint import pprint<br><br>import pandas as pd<br>import torch<br>from datasets import Dataset, load_dataset<br>from huggingface_hub import notebook_login<br>from peft import LoraConfig, PeftModel<br>from transformers import (<br>    AutoModelForCausalLM,<br>    AutoTokenizer,<br>    BitsAndBytesConfig,<br>    TrainingArguments,<br>)<br>from trl import SFTTrainer<br><br>DEVICE = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>MODEL_NAME = &quot;meta-llama/Llama-2-7b-chat-hf&quot;</pre><p><strong>2. Selecting and Cleaning our Dataset</strong></p><p>For this tutorial, we’re utilizing the ‘Dialog Studio’ dataset from Salesforce, available on Hugging Face. This collection is a rich resource for conversational AI research, and specifically, we’ll focus on the ‘TweetSumm’ subset.</p><p>The ‘TweetSumm’ dataset is structured as follows (for detailed information, please refer to the provided <a href="https://huggingface.co/datasets/Salesforce/dialogstudio/viewer/TweetSumm">link</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BV-R-Ic6pdD30ecPK2JHyA.png" /><figcaption>This is what the dataset looks like, please see link above for more information</figcaption></figure><pre>dataset = load_dataset(&quot;Salesforce/dialogstudio&quot;, &quot;TweetSumm&quot;)<br>dataset</pre><p>Data Pre-processing</p><p>Our first step is to preprocess the data, extracting meaningful conversations. The pre-processing involves creating a training prompt and cleaning the text to enhance the dataset’s usability. Here’s how we approach it:</p><p>We define a default prompt to guide the summarization task.</p><pre>DEFAULT_SYSTEM_PROMPT = &quot;&quot;&quot;<br>Below is a conversation between a human and an AI agent. Write a summary of the conversation.<br>&quot;&quot;&quot;.strip()<br><br><br>def generate_training_prompt(<br>    conversation: str, summary: str, system_prompt: str = DEFAULT_SYSTEM_PROMPT<br>) -&gt; str:<br>    return f&quot;&quot;&quot;### Instruction: {system_prompt}<br><br>### Input:<br>{conversation.strip()}<br><br>### Response:<br>{summary}<br>&quot;&quot;&quot;.strip()</pre><p>Cleaning and Formatting Text: We employ functions to clean and format the conversation text, removing unnecessary elements like URLs, user mentions, and extra spaces.</p><p>Creating Training Data: The key to our dataset preparation is generating summaries for each conversation. This involves piecing together the dialogues and their corresponding summaries, formatted for effective training.</p><pre>def clean_text(text):<br>    text = re.sub(r&quot;http\S+&quot;, &quot;&quot;, text)<br>    text = re.sub(r&quot;@[^\s]+&quot;, &quot;&quot;, text)<br>    text = re.sub(r&quot;\s+&quot;, &quot; &quot;, text)<br>    return re.sub(r&quot;\^[^ ]+&quot;, &quot;&quot;, text)<br><br><br>def create_conversation_text(data_point):<br>    text = &quot;&quot;<br>    for item in data_point[&quot;log&quot;]:<br>        user = clean_text(item[&quot;user utterance&quot;])<br>        text += f&quot;user: {user.strip()}\n&quot;<br><br>        agent = clean_text(item[&quot;system response&quot;])<br>        text += f&quot;agent: {agent.strip()}\n&quot;<br><br>    return text<br><br>#Most important part here is getting the summaries<br>def generate_text(data_point):<br>    summaries = json.loads(data_point[&quot;original dialog info&quot;])[&quot;summaries&quot;][<br>        &quot;abstractive_summaries&quot;<br>    ]<br>    summary = summaries[0]<br>    summary = &quot; &quot;.join(summary)<br><br>    conversation_text = create_conversation_text(data_point)<br>    return {<br>        &quot;conversation&quot;: conversation_text,<br>        &quot;summary&quot;: summary,<br>        &quot;text&quot;: generate_training_prompt(conversation_text, summary),<br>    }</pre><p>See sample conversations below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2skVTaw_KyfYqxXDpliaTw.png" /><figcaption>Sample conversations</figcaption></figure><p>Processing the Dataset</p><p>With our functions in place, we shuffle the original dataset and remove unnecessary columns to streamline it for training:</p><pre>def process_dataset(data: Dataset):<br>    return (<br>        data.shuffle(seed=42)<br>        .map(generate_text)<br>        .remove_columns(<br>            [<br>                &quot;original dialog id&quot;,<br>                &quot;new dialog id&quot;,<br>                &quot;dialog index&quot;,<br>                &quot;original dialog info&quot;,<br>                &quot;log&quot;,<br>                &quot;prompt&quot;,<br>            ]<br>        )<br>    )</pre><pre>dataset[&quot;train&quot;] = process_dataset(dataset[&quot;train&quot;])<br>dataset[&quot;validation&quot;] = process_dataset(dataset[&quot;validation&quot;])<br>dataset</pre><p>With our data now meticulously cleaned and prepared, we’re set to load the model for the fine-tuning process.</p><p><strong>3. Model Loading and Training</strong></p><p>Initiating the Hugging Face Environment. First, log into Hugging Face to access your account and models:</p><pre>notebook_login()</pre><p>Setting Up the LLaMA 2 Model</p><p>We proceed to load the LLaMA 2 model from Hugging Face. In this step, we utilize the Bits and Bytes library for quantization and define our tokenizer:</p><p>Configuring Model Parameters</p><p>We adjust the model’s configuration to disable caching and specify quantization settings:</p><p>Preparing the PEFT Configuration</p><p>We apply the PEFT (Parameter-efficient Fine-tuning) method with LoRA (Low-Rank Adaptation) configurations, optimizing the model for causal language modeling:</p><pre>def create_model_and_tokenizer():<br>    bnb_config = BitsAndBytesConfig(<br>        load_in_4bit=True,<br>        bnb_4bit_quant_type=&quot;nf4&quot;,<br>        bnb_4bit_compute_dtype=torch.float16,<br>    )<br><br>    model = AutoModelForCausalLM.from_pretrained(<br>        MODEL_NAME,<br>        use_safetensors=True,<br>        quantization_config=bnb_config,<br>        trust_remote_code=True,<br>        device_map=&quot;auto&quot;,<br>    )<br><br>    tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)<br>    tokenizer.pad_token = tokenizer.eos_token<br>    tokenizer.padding_side = &quot;right&quot;<br><br>    return model, tokenizer</pre><pre>model, tokenizer = create_model_and_tokenizer()<br>model.config.use_cache = False</pre><pre>model.config.quantization_config.to_dict()</pre><pre>lora_r = 16<br>lora_alpha = 64<br>lora_dropout = 0.1<br>lora_target_modules = [<br>    &quot;q_proj&quot;,<br>    &quot;up_proj&quot;,<br>    &quot;o_proj&quot;,<br>    &quot;k_proj&quot;,<br>    &quot;down_proj&quot;,<br>    &quot;gate_proj&quot;,<br>    &quot;v_proj&quot;,<br>]<br><br><br>peft_config = LoraConfig(<br>    r=lora_r,<br>    lora_alpha=lora_alpha,<br>    lora_dropout=lora_dropout,<br>    target_modules=lora_target_modules,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;,<br>)</pre><p>Here we use quantization and Lora Config and task type Casual_LM just predicts the next token.</p><p>Monitoring Training Performance</p><p>We observe the training progress by evaluating both the evaluation and training loss metrics, ensuring the training is proceeding effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMSnJGUSQpJ-9yAB-fS7ow.png" /><figcaption>Look at eval/loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faV5kH-SEUP3SXyr8QH_Gw.png" /><figcaption>Look at train/loss</figcaption></figure><p>Next, we set up our training arguments. These parameters are crucial for optimizing the model training process:</p><pre>training_arguments = TrainingArguments(<br>    per_device_train_batch_size=4,<br>    gradient_accumulation_steps=4,<br>    optim=&quot;paged_adamw_32bit&quot;,<br>    logging_steps=1,<br>    learning_rate=1e-4,<br>    fp16=True,<br>    max_grad_norm=0.3,<br>    num_train_epochs=2,<br>    evaluation_strategy=&quot;steps&quot;,<br>    eval_steps=0.2,<br>    warmup_ratio=0.05,<br>    save_strategy=&quot;epoch&quot;,<br>    group_by_length=True,<br>    output_dir=OUTPUT_DIR,<br>    report_to=&quot;tensorboard&quot;,<br>    save_safetensors=True,<br>    lr_scheduler_type=&quot;cosine&quot;,<br>    seed=42,<br>)</pre><p>Below is a list of hyperparameters that can be used to optimize the training process:</p><ul><li><strong>output_dir: </strong>The output directory is where the model predictions and checkpoints will be stored.</li><li><strong>num_train_epochs:</strong> One training epoch.</li><li><strong>fp16/bf16: </strong>Disable fp16/bf16 training.</li><li><strong>per_device_train_batch_size:</strong> Batch size per GPU for training.</li><li><strong>per_device_eval_batch_size:</strong> Batch size per GPU for evaluation.</li><li><strong>gradient_accumulation_steps:</strong> This refers to the number of steps required to accumulate the gradients during the update process.</li><li><strong>gradient_checkpointing:</strong> Enabling gradient checkpointing.</li><li><strong>max_grad_norm:</strong> Gradient clipping.</li><li><strong>learning_rate:</strong> Initial learning rate.</li><li><strong>weight_decay: </strong>Weight decay is applied to all layers except bias/LayerNorm weights.</li><li><strong>Optim:</strong> Model optimizer (AdamW optimizer).</li><li><strong>lr_scheduler_type:</strong> Learning rate schedule.</li><li><strong>max_steps:</strong> Number of training steps.</li><li><strong>warmup_ratio:</strong> Ratio of steps for a linear warmup.</li><li><strong>group_by_length:</strong> This can significantly improve performance and accelerate the training process.</li><li><strong>save_steps:</strong> Save checkpoint every 25 update steps.</li><li>logging_steps: Log every 25 update steps.</li></ul><p>Model Fine-Tuning Process</p><p>The fine-tuning process involves using the SFT (Supervised Fine-Tuning) Trainer from the TRL library. This tool simplifies training language models with reinforcement learning techniques:</p><p>Supervised fine-tuning (SFT) plays a crucial role in the process of Reinforcement Learning from Human Feedback (RLHF). The TRL library, offered by HuggingFace, features a user-friendly API that simplifies the creation and training of SFT models. With just a few lines of code, you can train your dataset effectively. This library includes a comprehensive toolkit for training language models via reinforcement learning, beginning with SFT, progressing through reward modeling, and culminating in Proximal Policy Optimization (PPO).</p><pre>trainer = SFTTrainer(<br>    model=model,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;validation&quot;],<br>    peft_config=peft_config,<br>    dataset_text_field=&quot;text&quot;,<br>    max_seq_length=4096,<br>    tokenizer=tokenizer,<br>    args=training_arguments,<br>)</pre><p>Training Loss Analysis</p><p>After training, we analyze the training loss to gauge the model’s performance and convergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*0ZmLAikkfR1TTvgUOXl5mA.png" /><figcaption>Training Loss</figcaption></figure><p>Saving the Model and Merging Adapters</p><p>Finally, we save the trained model and merge the QLoRA adapter for optimal performance:</p><pre>trainer.save_model()<br>trainer.model</pre><pre>from peft import AutoPeftModelForCausalLM<br><br>trained_model = AutoPeftModelForCausalLM.from_pretrained(<br>    OUTPUT_DIR,<br>    low_cpu_mem_usage=True,<br>)<br><br>merged_model = trained_model.merge_and_unload()<br>merged_model.save_pretrained(&quot;merged_model&quot;, safe_serialization=True)<br>tokenizer.save_pretrained(&quot;merged_model&quot;)</pre><p><strong>4. Inference: Evaluating Model Performance</strong></p><p>Preparing Test Examples: to assess our model’s effectiveness, we select five examples from the test dataset that the model has never encountered before:</p><pre>def generate_prompt(<br>    conversation: str, system_prompt: str = DEFAULT_SYSTEM_PROMPT<br>) -&gt; str:<br>    return f&quot;&quot;&quot;### Instruction: {system_prompt}<br><br>### Input:<br>{conversation.strip()}<br><br>### Response:<br>&quot;&quot;&quot;.strip()<br><br>examples = []<br>for data_point in dataset[&quot;test&quot;].select(range(5)):<br>    summaries = json.loads(data_point[&quot;original dialog info&quot;])[&quot;summaries&quot;][<br>        &quot;abstractive_summaries&quot;<br>    ]<br>    summary = summaries[0]<br>    summary = &quot; &quot;.join(summary)<br>    conversation = create_conversation_text(data_point)<br>    examples.append(<br>        {<br>            &quot;summary&quot;: summary,<br>            &quot;conversation&quot;: conversation,<br>            &quot;prompt&quot;: generate_prompt(conversation),<br>        }<br>    )<br>test_df = pd.DataFrame(examples)<br>test_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCXGB3xVU-PHX_O5aFIxsg.png" /><figcaption>The 5 examples from test dataset</figcaption></figure><p>Base Model Inference: initially, we perform inference using the base model to establish a benchmark:</p><pre>model, tokenizer = create_model_and_tokenizer()</pre><pre><br>def summarize(model, text: str):<br>    inputs = tokenizer(text, return_tensors=&quot;pt&quot;).to(DEVICE)<br>    inputs_length = len(inputs[&quot;input_ids&quot;][0])<br>    with torch.inference_mode():<br>        outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.0001)<br>    return tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)</pre><p>Above function just summarizes some text by passing in the tokenizer.</p><p><strong>Observations from Base Model Inference</strong><br>In the third example of inference with the base model, we notice that the output closely resembles the input, indicating inadequate summarization capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWTkQiesndgC22Z_gitsLQ.png" /><figcaption>Input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiL5QHsLUTfVtvxP_XLC8Q.png" /><figcaption>Output Summary</figcaption></figure><p><strong>Enhanced Inference with the Fine-Tuned Model</strong></p><p>Next, we switch to our fine-tuned model, which exhibits a marked improvement in performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ue2gMprhW4du9KdBTd2yEg.png" /><figcaption>Example 2 input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-QHofc5pXGTqC06rXi94A.png" /><figcaption>Example 2 output</figcaption></figure><p><strong>Comparison and Results</strong></p><p>Upon comparing the outputs, we observe that the fine-tuned model’s summarization is significantly more accurate and coherent. The summary generated by the fine-tuned model is substantially more effective, showcasing the benefits of our training process.</p><p><strong>Conclusion: Embracing Open Source AI with LLaMA 2</strong></p><p>As we conclude this guide on fine-tuning LLaMA 2, it’s evident that the AI landscape of 2023 isn’t solely defined by high-profile projects like ChatGPT, but also by the groundbreaking advancements in open-source AI. LLaMA’s emergence as an open-source large language model has been a game-changer, democratizing AI by enabling a wide array of developers and smaller organizations to contribute to and benefit from advanced AI technologies. This shift towards open-source AI is not just a trend but a movement towards more collaborative and inclusive AI development, where resources and knowledge are shared, empowering a larger community to innovate and grow.</p><p>In this journey, we’ve explored the potential of LLaMA 2, demonstrating that even with limited resources, one can achieve significant advancements. The techniques of PEFT, LoRA, and QLoRA exemplify efficient fine-tuning, making sophisticated AI models more accessible and adaptable. The essence of 2023’s AI story, therefore, lies in the fusion of technological advancement with the spirit of open-source collaboration, paving the way for a future where AI is more accessible, inclusive, and innovative.</p><p><strong>Link to notebook:</strong></p><p><a href="https://colab.research.google.com/drive/1PWw9zf5sqdFonFGE-D7_BgkvpaE-GCSl?usp=sharing">Google Colaboratory</a></p><p><strong>Resources</strong></p><ul><li><a href="https://ai.meta.com/llama/">https://ai.meta.com/llama/</a></li><li><a href="https://ai.meta.com/llama/get-started/">https://ai.meta.com/llama/get-started/</a></li><li><a href="https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/">https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/</a></li><li><a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/llama.cpp</a></li><li><a href="https://pytorch.org/blog/introduction-to-quantization-on-pytorch/">https://pytorch.org/blog/introduction-to-quantization-on-pytorch/</a></li><li><a href="https://huggingface.co/datasets/financial_phrasebank">https://huggingface.co/datasets/financial_phrasebank</a></li><li><a href="https://www.datacamp.com/tutorial/fine-tuning-llama-2">https://www.datacamp.com/tutorial/fine-tuning-llama-2</a></li><li><a href="https://huggingface.co/docs/optimum/concept_guides/quantization">https://huggingface.co/docs/optimum/concept_guides/quantization</a></li><li><a href="https://huggingface.co/datasets/Salesforce/dialogstudio/viewer/TweetSumm">https://huggingface.co/datasets/Salesforce/dialogstudio/viewer/TweetSumm</a></li><li><a href="https://mlabonne.github.io/blog/posts/Fine_Tune_Your_Own_Llama_2_Model_in_a_Colab_Notebook.html">https://mlabonne.github.io/blog/posts/Fine_Tune_Your_Own_Llama_2_Model_in_a_Colab_Notebook.html</a></li><li><a href="https://venturebeat.com/ai/forget-chatgpt-why-llama-and-open-source-ai-win-2023/">https://venturebeat.com/ai/forget-chatgpt-why-llama-and-open-source-ai-win-2023/</a></li><li><a href="https://forums.developer.nvidia.com/t/a100-vs-v100-for-ml-training/171230">https://forums.developer.nvidia.com/t/a100-vs-v100-for-ml-training/171230</a></li><li><a href="https://huggingface.co/blog/stackllama">https://huggingface.co/blog/stackllama</a></li><li><a href="https://huggingface.co/docs/trl/index">https://huggingface.co/docs/trl/index</a></li><li><a href="https://github.com/facebookresearch/llama-recipes">https://github.com/facebookresearch/llama-recipes</a></li><li><a href="https://cloud.google.com/model-garden">https://cloud.google.com/model-garden</a></li><li><a href="https://github.com/huggingface/peft">https://github.com/huggingface/peft</a></li><li><a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard">https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d3dad84202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Was Sam Altman Fired Due to an AGI Breakthrough?]]></title>
            <link>https://medium.com/@aditya.addy.bahl/was-sam-altman-fired-due-to-an-agi-breakthrough-143878285c53?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/143878285c53</guid>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[ai-regulation]]></category>
            <category><![CDATA[sam-altman]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 22:28:05 GMT</pubDate>
            <atom:updated>2023-11-21T22:28:05.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>Was Sam Altman Fired Due to an AGI Breakthrough? Exploring AI Regulation &amp; the Risk of Regulatory Capture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5G7YWquzrXNvopw8njTmJg.png" /></figure><p>Wow, what a week it has been! The AI community was shocked to receive the notification that Sam Altman, founder and CEO of OpenAI, was fired. This surprising news was not even communicated to Satya Nadella, CEO of Microsoft and OpenAI’s biggest investor with a $13 billion investment. This incident draws parallels to Steve Jobs’ firing from Apple in 1985, before his triumphant return and subsequent success. Efforts to reinstate Sam have been made, but the reasons behind his ousting remain a mystery. Below, I offer my insights on why Sam was fired, following a recap of the events that unfolded.</p><p><strong>What actually happened and what is going on?</strong></p><ul><li>On Friday, November 17, 2023, Sam Altman was fired by OpenAI’s board of directors for being “not consistent with his communication.”</li><li>OpenAI employees rallied behind Sam, leading to the resignation of Co-founder and Chairman Greg Brockman.</li><li>On Sunday, November 19, 2023, the board attempted to reverse course but could not agree on a governance structure to reinstate Sam, and appointed Emmett Sheer, former CEO of Twitch, as the interim CEO.</li><li>On Monday morning, November 20, 2023, Satya Nadella announced Microsoft’s continued commitment to OpenAI and stated that Sam, Greg, and most of OpenAI’s talent would join Microsoft to lead a new internal AI team.</li><li>The deal with Microsoft has not yet been finalized.</li><li>Ilya Sutskever, Chief Scientist of OpenAI and a major advocate for Altman’s firing, changed his stance and expressed deep regret for his involvement.</li><li>Despite Satya Nadella’s tweet, Sam is still attempting to return as CEO of OpenAI.</li><li>OpenAI’s board approached Anthropic, its biggest competitor, to discuss a merger, but the proposal was declined.</li></ul><p>So, will Sam return as CEO of Open AI? Will Sam start a new AI company under Microsoft? Did some new advancement scare the board?</p><p><strong>My Thoughts</strong></p><p>I believe Sam Altman’s firing from OpenAI was precipitated by a significant breakthrough outside their established transformer program. Recently, Sam revealed that a major advancement occurred, stating, “Four times now in OpenAI’s history — the most recent being just a few weeks ago — I’ve been present when we’ve pushed back the veil of ignorance.” The first three breakthroughs were in:</p><ol><li>RL (“Proximal Policy Optimization Algorithms”)</li><li>Dall-e (“Zero-Shot Text-to-Image Generation”)</li><li>Transformers/GPT (“Language Models as Few-Shot Learners”)</li></ol><p>All representing novel architectures rather than improvements on existing ones.</p><p>This latest breakthrough, I suspect, goes beyond merely scaling up transformers. Sam discussed on a podcast with Lex Friedman and in his Oxford Union address the necessity of a novel approach to reach Artificial General Intelligence (AGI), diverging from the mere enhancement of Large Language Models (LLMs). This perspective contrasts with Ilya Sutskever’s, OpenAI’s Chief Scientist and co-founder, who believes in the potential of GPT’s architecture and transformers to achieve AGI. Perhaps Sam’s discretion regarding this research led the board to deem him “not consistent with his communication.”</p><p>In this exciting era of AI development, the need for appropriate safety measures is paramount to ensure responsible deployment of AI. Furthermore, while effective legislation is needed to establish these safety guardrails, it’s critical to ensure such laws do not lead to regulatory capture, thereby stifling innovation.</p><p><strong>The Balancing Act of AI Regulation: From the EU Summit to Biden’s Executive Order and Beyond</strong></p><p>Navigating the path of AI regulation requires a delicate balance: enough to ensure safety and ethical use, but not so much that it stifles innovation. This balance is crucial for nurturing the burgeoning AI landscape while safeguarding public interest.</p><p>The EU AI Safety Summit took significant strides in this direction, emphasizing international cooperation to address AI’s risks while fostering innovation. The establishment of the AI Safety Institute and the Bletchley Declaration on AI Safety are testaments to a collective commitment to responsible AI development.</p><p>In the U.S., President Biden’s Executive Order on AI Safety aligns with these goals, emphasizing safe, secure, and equitable AI development. <strong>However, the executive order primarily focuses on systems and methods rather than outcomes and applications of AI, potentially overlooking the real-world impacts of AI deployment.</strong> Some critics have pointed out that the language in the order is vague, raising concerns about the creation of a federal regulatory body for software and possibly leading to confusion.</p><p>Furthermore, as venture capitalist Bill Gurley highlighted in his speech “2,851 Miles,” the risk of regulatory capture is a critical concern. This scenario, where industry leaders like OpenAI could unduly influence the regulations meant to govern them, could lead to a concentration of power that stifles competition and innovation, contradicting the goals of responsible AI development (We may not have to worry about that if most of Open AI’s employees leave).</p><p>In summary, while the EU’s summit and Biden’s executive order represent significant progress in AI governance, they are not without their criticisms and risks, including the potential for regulatory capture. Constant vigilance and a focus on real-world impacts are essential for ensuring that AI regulation advances in a manner that benefits all.</p><p><strong>Key Takeaways</strong></p><ol><li><strong>Major AGI Breakthrough: </strong>This week’s events suggest that Sam Altman’s dismissal may be attributed to a groundbreaking advancement in AGI, developed beyond the transformer project, with Ilya Sutskever possibly being excluded from the loop. This indicates a pivotal shift in OpenAI’s internal dynamics and strategic direction.</li><li><strong>Companies cannot regulate themselves: </strong>We need good clear AI regulation</li><li><strong>A Shift Towards Outcome-Based AI Regulation: </strong>There’s a growing need for regulations that focus on the outcomes and applications of AI, rather than just the systems and methods. This perspective is somewhat at odds with the approach proposed in President Biden’s AI Executive Order, highlighting the necessity of evolving our regulatory focus to address the real-world impacts of AI deployment more effectively.</li></ol><p><strong>References</strong></p><ol><li><a href="https://openai.com/blog/openai-announces-leadership-transition">https://openai.com/blog/openai-announces-leadership-transition</a></li><li><a href="https://www.reuters.com/technology/sam-altmans-firing-openai-reflects-schism-over-future-ai-development-2023-11-20/?utm_source=www.bigbraindaily.com&amp;utm_medium=newsletter&amp;utm_campaign=the-sam-altman-and-openai-breakup">https://www.reuters.com/technology/sam-altmans-firing-openai-reflects-schism-over-future-ai-development-2023-11-20/?utm_source=www.bigbraindaily.com&amp;utm_medium=newsletter&amp;utm_campaign=the-sam-altman-and-openai-breakup</a></li><li><a href="https://twitter.com/thecaptain_nemo/status/1725743009629983215">https://twitter.com/thecaptain_nemo/status/1725743009629983215</a></li><li><a href="https://www.linkedin.com/feed/update/urn:li:activity:7132734826951913472/">https://www.linkedin.com/feed/update/urn:li:activity:7132734826951913472/</a></li><li><a href="https://twitter.com/burny_tech/status/1725233117055553938">https://twitter.com/burny_tech/status/1725233117055553938</a></li><li><a href="https://www.morningbrew.com/daily/stories/2023/11/20/sam-altman-s-firing-was-a-battle-for-ai-s-soul?mbcid=33436848.1046698&amp;mid=9812273da450db8fd6a242aa70403ca0&amp;utm_campaign=mb&amp;utm_medium=newsletter&amp;utm_source=morning_brew">https://www.morningbrew.com/daily/stories/2023/11/20/sam-altman-s-firing-was-a-battle-for-ai-s-soul?mbcid=33436848.1046698&amp;mid=9812273da450db8fd6a242aa70403ca0&amp;utm_campaign=mb&amp;utm_medium=newsletter&amp;utm_source=morning_brew</a></li><li><a href="https://fortune.com/2023/09/17/bill-gurley-warns-regulatory-capture-ai-hails-open-source/">https://fortune.com/2023/09/17/bill-gurley-warns-regulatory-capture-ai-hails-open-source/</a></li><li><a href="https://twitter.com/rowancheung/status/1725960831815254024?s=20&amp;utm_source=www.therundown.ai&amp;utm_medium=newsletter&amp;utm_campaign=openai-board-goes-insane">https://twitter.com/rowancheung/status/1725960831815254024?s=20&amp;utm_source=www.therundown.ai&amp;utm_medium=newsletter&amp;utm_campaign=openai-board-goes-insane</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=143878285c53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operationalizing Generative AI, AI Agents Workforce, & Hallucinations]]></title>
            <link>https://medium.com/aimonks/operationalizing-generative-ai-ai-agents-workforce-hallucinations-78a880401b38?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a880401b38</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[hallucinations]]></category>
            <category><![CDATA[chatdev]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 20:34:37 GMT</pubDate>
            <atom:updated>2023-10-03T09:18:19.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmH09vIERiFIcstqZbIMNA.png" /></figure><p>Most CEOs are asking their teams and themselves how they can incorporate generative AI into their companies to increase business value. There has been a lot of buzz around generative AI and its many tasks, such as generating code, marketing content, realistic images, music, and automating many tasks. Sequoia Capital’s recent blog post spoke about how generative AI is entering its Act 2 and will be focused on solving human problems from beginning to end. What is different about Act 2 is that foundational models will be part of a more comprehensive solution, rather than the entire solution. Nonetheless, many are questioning why adoption by enterprises has been so slow. There are many variables, but two of the most important ones are hallucinations and data privacy.</p><p><strong>Operationalizing Generative AI</strong></p><p>Enterprises need to start by focusing on low-hanging fruit and start with problems that can be fixed today. Enterprises need to start by clearly defining the business problem and then figure out how to use generative AI. Compared to the old classical ML lifecycle, we can now store a bunch of data in a vector store and get analysis on that data very quickly. We do need to be mindful about what data we are inserting in the vector database to avoid the garbage in and garbage out problem. Thus, a great amount of time needs to be spent on creating a highly curated knowledge base.</p><p>This past week Microsoft just announced their AI Copilot, your everyday AI companion that will help you work faster and smarter. It is integrated into Microsoft 365 apps, such as Word, Excel, PowerPoint, Outlook, and Teams, and provides real-time assistance with tasks such as:</p><ul><li>Writing and editing: Copilot can help you write and edit documents, emails, and presentations by suggesting relevant content, correcting grammar and spelling errors, and improving your writing style.</li><li>Research and analysis: Copilot can help you research and analyze data by extracting key insights from documents, translating languages, and creating charts and graphs.</li><li>Collaboration and communication: Copilot can help you collaborate and communicate more effectively by summarizing key points from meetings, generating talking points, and translating languages.</li></ul><p>Microsoft Copilot is still under development, but it has the potential to revolutionize the way we work. By providing real-time assistance with a wide range of tasks, Copilot can help us to be more productive, efficient, and creative.</p><p><strong>ChatDev — Communicative Agents for Software Development</strong></p><p>I am very excited and bullish on the future of multiple AI agents communicating with one another to complete complex tasks. It is a new framework and does not always work as intended currently, but it is going to change the way all knowledge work is done. This past week, I was experimenting with ChatDev, a virtual software company where multiple intelligent agents holding different roles communicate with one another to complete the task assigned. Some of the roles include Chief Executive Officer, Chief Technology Officer, Chief Product Officer, Programmer, Code Reviewer, Tester, and more. These are some of the roles provided in the original repository, but roles can be customized. I was testing its limits and was surprised that with just this simple command, I was able to generate a pingpong game, and it produced all of the documentation and instructions on how to play the game.</p><pre>python3 run.py --task &quot;Develop a simple pingpong game.&quot; --name &quot;pingpong&quot;</pre><p>Results may vary on each generation. I had some fun with prompt engineering!</p><p>An AI agent workforce has the potential to revolutionize the way we work by automating tasks, making better decisions, and fostering creativity and innovation.</p><p>By working together, AI agents can accomplish tasks more quickly, accurately, and efficiently than humans alone. They can also analyze large amounts of data to identify patterns and trends that would be difficult for humans to see. This information can then be used to inform decisions and make better predictions. Additionally, AI agents can be used to generate new ideas and solutions to problems, helping us to be more creative and innovative.</p><p>As AI technology continues to develop, AI agent workforces are poised to play an increasingly important role in our lives.</p><p><strong>Hallucinations</strong></p><p>What do hallucinations even mean? As Marc Benioff explained during Salesforce’s Dreamforce keynote, “These things are good, but they’re not great,” Benioff said. “You get a lot of answers that aren’t exactly true. They call them hallucinations. I call it lies … and they can turn very toxic very quickly.”</p><p>Based on conversations I have had with executives recently, hallucinations are the main thing that is preventing many CEOs from deploying LLM solutions into production. Hallucinations are false or misleading statements that LLMs can generate, often due to a lack of understanding of the underlying reality that language describes.</p><p>Hallucinations can be a serious problem for enterprises, as they can lead to inaccurate information being provided to customers or investors, or to decisions being made based on false premises. For example, an LLM used to generate marketing copy could hallucinate about product features that do not exist, or an LLM used to generate financial reports could hallucinate about financial data that is inaccurate.</p><p>There are a number of reasons why LLMs are prone to hallucinations. First, LLMs are trained on massive datasets of text and code, but these datasets often contain errors and inconsistencies. This means that LLMs can learn to generate text that is factually incorrect or misleading. Second, LLMs are statistical models, and they do not have any understanding of the real world. This means that they can generate text that is grammatically correct and semantically coherent, but that is still false or misleading.</p><p>While there are a number of techniques that can be used to mitigate the risk of hallucinations in LLMs, these techniques are not perfect. As a result, enterprises are hesitant to deploy LLMs in production environments.</p><p>Overall, the risk of hallucinations is a major barrier to the adoption of LLMs by enterprises. However, as research into hallucination mitigation techniques continues, it is likely that LLMs will become more widely deployed in enterprise environments in the near future.</p><p><strong>Let’s Chat!</strong></p><p>If you’re interested in chatting more about enterprise use cases for LLMs, AI agents, and AI safety, or if you have any questions or feedback, please feel free to send me a message. I’m always happy to chat about these topics.</p><p>Cheers!</p><p>Aditya Bahl</p><p><strong>References</strong></p><ol><li><a href="https://www.sequoiacap.com/article/generative-ai-act-two/">https://www.sequoiacap.com/article/generative-ai-act-two/</a></li><li><a href="https://www.salesforce.com/dreamforce/">https://www.salesforce.com/dreamforce/</a></li><li><a href="https://blogs.microsoft.com/blog/2023/09/21/announcing-microsoft-copilot-your-everyday-ai-companion/">https://blogs.microsoft.com/blog/2023/09/21/announcing-microsoft-copilot-your-everyday-ai-companion/</a></li><li><a href="https://github.com/OpenBMB/ChatDev">https://github.com/OpenBMB/ChatDev</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a880401b38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/operationalizing-generative-ai-ai-agents-workforce-hallucinations-78a880401b38">Operationalizing Generative AI, AI Agents Workforce, &amp; Hallucinations</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Addy’s Top AI Predictions for 2023]]></title>
            <link>https://medium.com/@aditya.addy.bahl/addys-top-ai-predictions-for-2023-b026f0f373c?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/b026f0f373c</guid>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 22:49:09 GMT</pubDate>
            <atom:updated>2023-01-03T23:03:59.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhS3l9HkcQJ79__yVOMM4Q.png" /></figure><p>As we enter 2023, it’s natural to wonder what the year has in store for artificial intelligence (AI). While it’s difficult to make precise predictions, there are a few key areas where we can expect to see significant advancements in AI over the course of the year. 2023 is going to be a fantastic year and here are a few topics that I’m currently pondering upon:</p><ol><li><strong>AI is eating the world 🌎 SaaS is Dying and MaaS is the future!</strong></li></ol><p>Software as a Service (SaaS) refers to a model in which software is delivered and accessed over the internet, rather than being installed locally on a user’s device. While SaaS has been a popular delivery model for software in recent years, it is now facing increasing competition from Models as a Service (MaaS). MaaS refers to a model in which users access and utilize trained machine learning models over the internet, rather than building and training their own models from scratch.</p><p>There are several reasons why MaaS is likely to surpass SaaS as the dominant delivery model for software in the future. First and foremost, MaaS allows organizations to leverage the latest and most powerful machine learning models without the need to invest in expensive hardware and software infrastructure. This makes it much easier and cost-effective for organizations to take advantage of the latest AI technologies. Additionally, MaaS allows organizations to access and utilize a wide range of specialized models, rather than being limited to a single software application. This makes it much more flexible and adaptable to changing business needs. Finally, MaaS allows organizations to scale their use of AI much more easily and efficiently, as they can simply access additional models as needed, rather than having to invest in additional hardware and software infrastructure. All of these factors make MaaS a more attractive and viable option for many organizations, and it is likely to become the dominant delivery model for software in the future.</p><p><strong>2. Why 2023 Will Be a Big Year for Generative AI 🧠</strong></p><p>2023 is likely to be a significant year for generative artificial intelligence (AI). Generative AI refers to a type of AI that is capable of generating novel content, such as text, images, or audio, based on a set of input parameters. There are several reasons why 2023 is likely to be a key year for generative AI.</p><p>First, the technological capabilities of generative AI are rapidly advancing, and we can expect to see significant improvements in the quality and diversity of the content generated by these systems in 2023. We are eagerly waiting for GPT-4! This will enable a wide range of new applications, from improved machine translation and natural language processing to more realistic and engaging virtual assistants and chatbots.</p><p>Second, there is increasing demand for generative AI from a variety of industries, including media, marketing, and advertising. In 2023, we can expect to see more organizations leveraging generative AI to create personalized content for their customers and to streamline their content creation processes.</p><p>Finally, the increasing adoption of generative AI is likely to drive further investments and research in the field, leading to even more rapid advancements in the technology. All of these factors make 2023 a key year for generative AI and its potential to transform a wide range of industries.</p><p><strong>3. Building Responsible AI ⛑️</strong></p><p>Building responsible artificial intelligence (AI) is a critical concern for researchers, developers, and users of AI systems. Responsible AI refers to the development and use of AI in a way that is ethical, transparent, and fair. This includes ensuring that AI systems do not discriminate against certain groups of people, do not perpetuate harmful biases, and are transparent in their decision-making processes.</p><p>However, this is already proving to be difficult as capturing cultural nuances is tough as the data sets used are inherently biased. One example is Tencent’s Different Dimension Me tool, which can turn people’s photos into anime characters. Nonetheless, users quickly realized that the tool failed to recognize black and plus-sized individuals, groups that are missing from Japanese anime, leading to offensive AI generated results.</p><p>There are several key considerations when building responsible AI. One important aspect is ensuring that AI systems are designed and trained on diverse and representative data sets, so that they do not perpetuate harmful biases or discrimination. Another key consideration is ensuring that AI systems are transparent in their decision-making processes, so that users and stakeholders can understand how they arrived at a particular decision. Finally, it is important to have robust processes in place for addressing and mitigating the risks and unintended consequences of AI, including the development of appropriate safeguards and accountability measures.</p><p>Building responsible AI requires a multi-faceted approach that involves the participation and collaboration of researchers, developers, and stakeholders from a wide range of disciplines. By working together and taking a responsible approach to AI development and use, we can ensure that this powerful technology is used for the benefit of all.</p><p><strong>4. The Future of Product Discovery: Social Media and Creator Videos 📱🎥</strong></p><p>In the coming years, it is likely that social media platforms will become an increasingly natural place for product discovery. This is because social media platforms are highly engaging and interactive, and they offer a wealth of user-generated content that can be used to showcase and promote products. In addition, social media platforms have a large and diverse user base, making them an ideal place to reach a wide range of potential customers.</p><p>One particularly effective way that products can be promoted on social media is through creator videos. Creator videos are videos produced by influencers or content creators that showcase and review products in an authentic and engaging way. These videos can be an extremely effective way to sell products, as they often have a high level of trust and credibility with viewers. In addition, creator videos can be highly engaging and entertaining, making them an effective way to capture the attention of potential customers.</p><p>Overall, social media platforms and creator videos are likely to become an increasingly important part of the product discovery and sales process in the coming years. By leveraging these channels, businesses will be able to reach and engage with a large and diverse audience in a natural and authentic way.</p><p><strong>5. China’s 🇨🇳 Generative AI rules set boundaries &amp; punishments for misuse</strong></p><p>As text to image generators like Stable diffusion and intelligent chatbots like ChatGPT knock people’s socks off, countries are becoming wary and scrambling to establish some regulation. China is actually at the forefront on regulating AI. The Cyberspace Administration of China, just passed regulation on “deep synthesis” technology, which will go into effect on January 10. Deep synthesis is defined as “technology that uses deep learning, virtual reality, and other synthesis algorithms to generate text, images, audio, video, and virtual scenes.”</p><p>Users are prohibited from using generative AI to engage in activities that endanger national security, damage public interest or are illegal. These restrictions are made possible by China’s real-name verification apparatus. Providers of generative AI are required to collect and verify users phone numbers and IDs. China wants to censor what algorithms can generate. As a country they already censor politically sensitive content, but are now going to make service providers audit AI-generated content and user prompts manually or through technical means.</p><p>Chinese government should get a little credit for stepping in to prevent misuse of AI. These rules will deter people from churning out NSFW / sexist content and disseminate fake news. Users who violate these regulations will face punishments.</p><p><strong>6. AI Companies Brace for Regulatory Changes — EU’s 🇪🇺 AI Act</strong></p><p>Regulations similar to EU’s AI Act may alter the way companies create and implement AI systems in the future. Regulations and content moderation will play a crucial role in trying to stop the spread of misinformation as they try to keep up with the sheer volume of synthetic data — text, audio, images, and videos that these AI models generate.</p><p>Currently the rules will divide AI systems into different risk categories. High-risk AI (ex. credit scoring algorithms, robotic surgery apps) will be required to meet legal, ethical, and technical standards before being permitted to enter the European market. Low-risk AI (ex spam filters, AI-video games) will only require that users be made aware that they are interacting with an AI system.</p><p>Proposed EU rules will have serious implications for cutting edge tools like GPT-3, Open AI Codex, Stable Diffusion, and the greater Open Source community.</p><p><strong>7. Synthetic Data &amp; Virtual Characters will play a crucial role in the success of the Metaverse 🕹️</strong></p><p>The metaverse, a virtual shared space that is created by the convergence of virtually enhanced physical reality and physically persistent virtual space, is gaining a lot of attention as a promising technology that has the potential to revolutionize various industries. While there are still many challenges that need to be addressed before the metaverse can fully realize its potential, it is clear that synthetic data and virtual characters will play a crucial role in its development and success.</p><p>Synthetic data, or data that is generated by a computer program rather than collected from the real world, has the potential to be a valuable resource for the metaverse. One of the main benefits of synthetic data is that it can be created in large quantities and can be customized to fit specific needs. This means that developers can use synthetic data to test and refine their metaverse applications without having to rely on real-world data, which can be expensive and time-consuming to collect.</p><p>In addition to synthetic data, virtual characters are also expected to play a crucial role in the metaverse. Virtual characters can be used to represent real people or to create entirely new, fictional characters. They can be used for a variety of purposes, including entertainment, education, and social interaction. By using virtual characters, developers can create engaging and immersive experiences for users within the metaverse.</p><p>Overall, it is clear that synthetic data and virtual characters will be key players in the development and success of the metaverse. As the technology continues to evolve and improve, we can expect to see even more innovative and exciting uses for these tools in the future.</p><p>I’m excited to see what the new year has in store for us. If you enjoyed this article, be on the lookout for more in the upcoming months. My focus will be on topics such as AI, LLMs, AI safety, venture capital trends, and building and scaling machine learning pipelines. To connect with me, you can follow me on <a href="https://twitter.com/aditya_bahl">Twitter</a>. Happy New Year! 🥳</p><p><em>PS: This article was co-written by my friend GPT-3. While the AI model didn’t generate the entire piece, it did assist with overcoming writer’s block, generating complete sentences and paragraphs, and brainstorming various applications for generative AI.</em></p><p>References:</p><ul><li><a href="https://openai.com/">OpenAI | Research &amp; Deployment</a></li><li><a href="https://artificialintelligenceact.eu/">EU Artificial Intelligence Act | Up-to-date developments and analyses of the EU AI Act</a></li><li><a href="https://techcrunch.com/2022/12/31/how-china-is-building-a-parallel-generative-ai-universe/">How China is building a parallel generative AI universe</a></li><li><a href="https://techcrunch.com/2022/12/13/chinas-generative-ai-rules-set-boundaries-and-punishments-for-misuse/">China&#39;s generative AI rules set boundaries and punishments for misuse</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b026f0f373c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use NLP to Take on Wall Street]]></title>
            <link>https://medium.com/@aditya.addy.bahl/how-to-use-nlp-to-take-on-wall-street-347f5fad0fcc?source=rss-5482e6712265------2</link>
            <guid isPermaLink="false">https://medium.com/p/347f5fad0fcc</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[wall-street-bets]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[ml-pipeline]]></category>
            <dc:creator><![CDATA[Aditya Bahl]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 22:11:29 GMT</pubDate>
            <atom:updated>2023-01-03T22:52:52.423Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to Build an End to End Production Machine Learning Pipeline to Track Sentiment of Financial News Headlines</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*UI2YiYVhDq7MNk5K7AxD4A.jpeg" /></figure><p><strong>What Happened With GameStop?</strong></p><p>In January, 2021, retail investors - Robinhood army - came together on Reddit’s Wall Street Bets group and other social media outlets to take down prominent hedge funds by causing a short squeeze and pushing up GameStop’s stock price by 400% in just one week¹. This amount of volatility is not normal, the retail investors were urged on by the Reddit group to punish hedge funds that had taken an outsized short bet against GameStop. Tracking market sentiment can be a powerful tool for investors because understanding the mood of where the market is going can allow one to capitalize from the changing direction. Combining market sentiment with market fundamentals will result in more sound investments.</p><p>I was fascinated by the showdown between Wall Street and Reddit and inspired to understand how machine learning (ML) can be used to track market sentiment. For my capstone project at University of California San Diego’s Machine Learning Engineering Bootcamp, I decided to build a sentiment classifier to determine the polarity of financial news headlines. The post goes through steps required to build an end to end pipeline — building and selecting the model that will be deployed to production, using Docker to build images, and using Kubernetes to manage the deployed containers and Flask application. In addition, this post will provide some background about what is machine learning, what is natural language processing(NLP), compare three state of the art NLP models: VADER, Google BERT, and Google XLNet, and explain how Google Cloud Storage is utilized.</p><p><strong>What is Machine Learning?</strong></p><p>Machine learning² is a subset of artificial intelligence (AI) and computer science which uses data and algorithms to imitate the way humans learn, gradually improving its accuracy. Previously, researchers gave the machines data and a set of rules to determine the Y output. However, recently the biggest breakthroughs have come from giving machines tons of data and the Y output, and letting the machine find the rules required to get that end result. It is a very important distinction to understand.</p><p><strong>What is NLP? How do Machines Understand What Humans are Talking About?</strong></p><p>Natural language processing³ (NLP) is another subset of artificial intelligence (AI) and computer science that seeks to give computers the ability to understand text and spoken words in the same way humans can. NLP combines computational linguistics — rule based modeling — with statistics, machine learning, and deep learning to understand the meaning of the text. For my capstone project, I compared three ML models — VADER, retrained Google’s BERT model, and retrained Google’s XLNET model.</p><p><strong>The Financial Phrase-Bank Dataset was Used for Training of The Models⁴</strong></p><p>It is a dataset consisting of 4,840 sentences from English language financial news headlines categorized by sentiment. The selected collection of sentences were annotated by 16 people with background in financial markets.</p><p><strong>VADER Model⁵ — Rule Based Model</strong></p><p>VADER ( Valence Aware Dictionary for Sentiment Reasoning) is a model used for sentiment analysis that determines both polarity (positive/negative) and intensity (strength) of emotion. The compound score is the sum of positive, negative, and neutral scores which is normalized between -1 (most extreme negative) and +1 (most extreme positive). Below is an example of what the output for the VADER model looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tRuvu2o_HSGxHYrk" /><figcaption>Example output of VADER model</figcaption></figure><p>To assess the performance of the VADER model, I looked at the confusion matrix and we can see that the VADER model had an accuracy of 60% when tested on the Financial Phrase-Bank dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*WWtfXWv9LT9JQM99" /><figcaption>Confusion Matrix of VADER Model</figcaption></figure><p>When building a ML pipeline it is important to try the easiest approach first and after trying the rule based model, we can see that it did not perform well and only got a 60% accuracy. So, the next step is to try machine learning approaches: instead of training a model from scratch, I decided to use a pre-trained general purpose language model and fine tune it on our specific task to determine polarity of news headlines.</p><p><strong>General Purpose Language Models — Transfer Learning⁶</strong></p><p>One of the biggest challenges in Natural Language processing (NLP) is the lack of training data. NLP is a diversified field with many different tasks, and datasets for those specific tasks are hard to come across and may only contain a few hundred thousand human-labeled training examples. However, modern deep learning models need large quantities of data as it leads to significant model performance when trained on millions or billions of data points. To bridge this gap, researchers have started using general purpose language representation models that are trained on an enormous amount of unannotated text during pre-training for simple tasks. Then, these general purpose pre-trained models can be fine-tuned on specific tasks which result in substantial accuracy improvements compared to training on just those datasets from scratch. Thus, knowledge gained from solving one problem can be applied to solving another different but related problem.</p><p><strong>Google’s BERT Model⁷</strong></p><p>Google’s Bidirectional Encoder Representations from Transformers (BERT) model is deep neural network technique for NLP pre-training. It is designed to pre-train deep bidirectional representations from unlabeled text by conditioning both left and right context in all layers. BERT outperformed other state of the art models by incorporating both left and right contexts into predictions. BERT’s training objective was to recover words in a sentence which have been masked. In a sentence, some tokens are replaced with a generic [mask] token, and the model is asked to recover the originals⁸.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIzzagaFfwFCCaQDJG-uBw.png" /><figcaption>BERT model — some of the input tokens are masked and it tries to predict the correct token</figcaption></figure><p>BERT is trained on a plain text corpus — Wikipedia. What makes BERT different? Pre-trained representations can be context-free or contextual. For example, the word “bank” would have the same context free representation in “bank account” and “bank of the river.” On the other hand, contextual models take into account other words in the sentence. Thus, what makes BERT special is that it is bidirectional. Below is a picture of BERT and other models architecture⁷.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4bx0x_1Qz45gmfCB" /></figure><p>The BERT model achieved an accuracy score of 51% without retraining when tested on the Financial Phrase-Bank dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*ut0XGDpyfx22sdSbZF0l-Q.png" /><figcaption>Confusion Matrix for BERT model without retraining</figcaption></figure><p>The BERT model can be fine-tuned with just one additional output layer to create state of the art models for a wide range of tasks⁹. Thus, I retrained Google’s BERT model for sentiment analysis on the Financial Phrase-Bank dataset and achieved an accuracy score of 81%. These notebooks can be accessed on my GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Az5yRfKitWEbQJw1-lsDjA.png" /><figcaption>Confusion Matrix of fine-tuned BERT model</figcaption></figure><p><strong>Google’s XLNet Model¹⁰</strong></p><p>The XLNet model builds upon BERT’s bidirectional contexts, but does not rely on corrupting the input with masks, like BERT does since it neglects dependency between masked positions. XLNet is an autoregressive language model that 1) learns bidirectional contexts by maximizing the expected likelihood over all permutations of the factorization order and 2) overcomes BERT’s limitations thanks to its autoregressive formulation.</p><p>XLNet’s main contribution is not its architecture, but it’s modified training objective which learns conditional distributions for all permutations of tokens in a sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csmuOrFltdRq8JPUpBzBAg.png" /><figcaption>XLNet model — must calculate that boat is likely token for many different contexts drawn from the sequence</figcaption></figure><p>XLNet is an auto-regressive over all permutations, it can calculate the probability of token X given preceding tokens from any order. This is done using permutation modeling and it’s two-stream self attention architecture. I have attached a picture below for the architecture and for more details about the inner workings of the XLNet model please refer to the research paper¹⁰.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeSAAZoRurNaLY-YxKHamg.png" /><figcaption>a): content stream attention b): query stream attention c): overview of permutation language modeling training with two-stream attention</figcaption></figure><p>The XLNet model achieved an accuracy score of 43% without retraining on the Financial Phrase-Bank dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*S6hGODBZkoMZ7CguV_w5Tg.png" /><figcaption>Confusion Matrix of XLNet model without retraining</figcaption></figure><p>After retraining Google’s XLNet on the Financial Phrase-Bank dataset, the model achieved an accuracy score of 86% and this is the model I used to deploy in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*dWcSKH-kSk36wLbK6onX_g.png" /><figcaption>Confusion Matrix of XLNet model after fine-tuning</figcaption></figure><p><strong>Time to Deploy the ML Model in Production</strong></p><p>The goal of the project was to develop an end to end pipeline and deploy it into production. Thus, the next step was to turn our Jupyter notebooks into Python scripts that can be used for production. I deployed the scripts as different services so they would not be dependent on each other, allowing for easier scalability.</p><p>Script 1 — Get the Stock Prices and Headlines</p><ul><li>It gets the stock price information and financial news headlines for the stocks in the Dow Jones Index.</li><li>First, it pulls the stock price information for the 30 stocks in the index using Yfinance’s API. That data is stored in a data frame and a CSV file is created.</li><li>Second, we use Finnhub’s API to get news headlines relevant to the stocks in the Dow Jones Index and those headlines are stored in another data frame and a CSV file is created for them.</li><li>Third, the stock price CSV and news headlines CSV file are both uploaded to Google Cloud storage.</li></ul><pre><strong><em># Script 1 - gets news headlines and stock price data</em></strong></pre><pre><strong><em># Import necessary packages</em></strong></pre><pre>import yfinance as yf<br>import json<br>import datetime<br>import requests<br>import pandas as pd<br>import pytz<br></pre><pre><strong><em># Set the start and end date</em></strong></pre><pre>start_date = datetime.datetime.now(pytz.timezone(&#39;US/Pacific&#39;)).strftime(&#39;%Y-%m-%d&#39;)<br>end_date = (datetime.datetime.now(pytz.timezone(&#39;US/Pacific&#39;)) + datetime.timedelta(days=1)).strftime(&#39;%Y-%m-%d&#39;)<br></pre><pre><strong><em># Opening JSON file - it has all the stock tickers</em></strong></pre><pre>f = open(&quot;config.json&quot;, )<br></pre><pre><strong><em># Returns JSON object as a dictionary</em></strong></pre><pre>config = json.loads(f.read())<br></pre><pre><strong><em># Function to get stock prices</em></strong></pre><pre>def get_stock_data(stockticker, startdate, enddate):<br>    data = yf.download(stockticker, startdate, enddate)<br>    data[&#39;name&#39;] = stockticker<br>    return data<br><br><strong><em># Function to get news headlines</em></strong></pre><pre>def get_news_data(stockticker, startdate, enddate):<br>    url = f&quot;https://finnhub.io/api/v1/company-news?symbol={stockticker}&amp;from={startdate}&amp;to={enddate}&amp;token=c2mnsqqad3idu4aicnrg&quot;<br>    r = requests.get(url)<br><br>    response = r.json()<br>    if not response:<br>        return pd.DataFrame(index=[&#39;datetime&#39;, &#39;headline&#39;, &#39;related&#39;, &#39;source&#39;])<br><br>    r2 = pd.DataFrame(response)<br>    df = r2[[&#39;datetime&#39;, &#39;headline&#39;, &#39;related&#39;, &#39;source&#39;]]<br>    return df<br><br><br><strong><em># Get stock information about multiple stocks</em></strong></pre><pre>stock_data_list = []<br><br>for ticker in config[&quot;stockticker&quot;].split():<br>    tmp = get_stock_data(ticker, start_date, end_date)<br>    if not tmp.empty:<br>        stock_data_list.append(tmp)<br><br>stock_data = pd.concat(stock_data_list)<br></pre><pre><strong><em># Get news information about multiple stocks</em></strong></pre><pre>news_data_list = []<br><br>for ticker in config[&quot;stockticker&quot;].split():<br>    tmp = get_news_data(ticker, start_date, end_date)<br>    if not tmp.empty:<br>        news_data_list.append(tmp)<br><br>news_data = pd.concat(news_data_list)<br><br><br><strong><em># Upload CSV files to Google cloud</em><br></strong><br>from google.cloud import storage<br>client = storage.Client.from_service_account_json(json_credentials_path=&#39;yourfile.json&#39;)<br>bucket = client.get_bucket(&#39;yourbucket1&#39;)<br>object_name_in_gcs_bucket = bucket.blob(&#39;stock_data.csv&#39;)<br>df = pd.DataFrame(data=stock_data).to_csv(encoding=&quot;UTF-8&quot;)<br>object_name_in_gcs_bucket.upload_from_string(data=df)<br><br>object_name_in_gcs_bucket = bucket.blob(&#39;news_data.csv&#39;)<br>df = pd.DataFrame(data=news_data).to_csv(encoding=&quot;UTF-8&quot;)<br>object_name_in_gcs_bucket.upload_from_string(data=df)</pre><p>Script 2 — Determine Sentiment of Headlines &amp; Create Processed File</p><ul><li>It first pulls the news headlines CSV file from Google Cloud.</li><li>Then, we load Google’s XLNet model with our pre-trained weights from our checkpoint file that we created when we fine-tuned the model for sentiment analysis based on the Financial Phrase-bank dataset. Then we do some data-preprocessing steps because the model takes input in a certain way (tokenize the inputs) and then the predict_sentiment function determines the polarity of a news headline.</li><li>Then, the second stock price CSV file is pulled from Google Cloud. The two data frames are concatenated and a completed processed CSV file is uploaded to another bucket on Google Cloud.</li><li>Then, on the Google Cloud Platform we used the Big Query database and linked it to Google storage buckets so the completed processed file was uploading data to the database.</li></ul><pre><strong><em># Model Inference</em><br></strong><br>import pandas as pd<br>import torch<br>import torch.nn.functional as F<br>from transformers import XLNetModel, XLNetTokenizer, XLNetForSequenceClassification<br>from keras.preprocessing.sequence import pad_sequences<br>import time<br>import io<br></pre><pre><strong><em># Get CSV files from Google Cloud</em></strong></pre><pre>from google.cloud import storage<br>client = storage.Client.from_service_account_json(json_credentials_path=&#39;yourfile.json&#39;)<br>bucket = client.bucket(&#39;yourbucket1&#39;)<br><br>blob = bucket.blob(&#39;news_data.csv&#39;)<br>blob.download_to_filename(&#39;data.csv&#39;)<br>df = pd.read_csv(&#39;data.csv&#39;)<br></pre><pre><strong><em># Load the XLNET model and pre-trained weights</em></strong></pre><pre>model = XLNetForSequenceClassification.from_pretrained(&quot;xlnet-base-cased&quot;, num_labels=3)<br><br>model.load_state_dict(torch.load(&quot;model_with_retraining.ckpt&quot;, map_location=torch.device(&#39;cpu&#39;)))<br># keep map_location<br># model.cuda()<br></pre><pre><strong><em># Prediction function to determine sentiment of news headlines</em></strong></pre><pre>def predict_sentiment(text):<br>    review_text = text<br><br>    encoded_review = tokenizer.encode_plus(<br>    review_text,<br>    max_length=MAX_LEN,<br>    add_special_tokens=True,<br>    return_token_type_ids=False,<br>    pad_to_max_length=False,<br>    return_attention_mask=True,<br>    return_tensors=&#39;pt&#39;,<br>    )<br><br>    input_ids = pad_sequences(encoded_review[&#39;input_ids&#39;], maxlen=MAX_LEN, dtype=torch.Tensor ,truncating=&quot;post&quot;,padding=&quot;post&quot;)<br>    input_ids = input_ids.astype(dtype = &#39;int64&#39;)<br>    input_ids = torch.tensor(input_ids)<br>    attention_mask = pad_sequences(encoded_review[&#39;attention_mask&#39;], maxlen=MAX_LEN, dtype=torch.Tensor ,truncating=&quot;post&quot;,padding=&quot;post&quot;)<br>    attention_mask = attention_mask.astype(dtype = &#39;int64&#39;)<br>    attention_mask = torch.tensor(attention_mask)<br><br>    input_ids = input_ids.reshape(1,128).to(device)<br>    attention_mask = attention_mask.to(device)<br><br>    outputs = model(input_ids=input_ids, attention_mask=attention_mask)<br>    outputs = outputs[0][0].cpu().detach()<br><br>    probs = F.softmax(outputs, dim=-1).cpu().detach().numpy().tolist()<br>    _, prediction = torch.max(outputs, dim =-1)<br><br>    target_names = [&#39;negative&#39;, &#39;neutral&#39;, &#39;positive&#39;]<br><br>    return probs, target_names[prediction]<br><br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br>tokenizer = XLNetTokenizer.from_pretrained(&#39;xlnet-base-cased&#39;)<br>MAX_LEN = 128<br><br>probs_list = []<br>prediction_list = []<br>for sentence in df[&#39;headline&#39;]:<br>    probs, prediction = predict_sentiment(sentence)<br>    probs_list.append(probs)<br>    prediction_list.append(prediction)<br><br>probs_df = pd.DataFrame(probs_list)<br>probs_df.columns = [&#39;negative&#39;, &#39;neutral&#39;, &#39;positive&#39;]<br><br>prediction_df = pd.DataFrame(prediction_list)<br>prediction_df.columns = [&#39;Sentiment&#39;]<br></pre><pre><strong><em># Classified news headlines</em></strong></pre><pre>final_df = pd.concat([df,probs_df,prediction_df], axis=1)<br>final_df[&quot;datetime&quot;] = pd.to_datetime(final_df[&quot;datetime&quot;], unit=&#39;s&#39;).dt.strftime(&#39;%Y-%m-%d&#39;)<br>final_df = final_df.rename(columns={&quot;datetime&quot;:&quot;Date&quot;})<br>final_df = final_df.rename(columns={&quot;related&quot;:&quot;name&quot;})<br><br><br><strong><em># Get Stock Price CSV and concatenate stock price and processed headlines into one CSV file</em></strong></pre><pre>blob = bucket.blob(&#39;stock_data.csv&#39;)<br>blob.download_to_filename(&#39;stock1.csv&#39;)<br>hist = pd.read_csv(&#39;stock1.csv&#39;)<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>complete_df = pd.merge(final_df, hist, how=&#39;left&#39;, on=[&#39;Date&#39;, &#39;name&#39;])<br></pre><pre><strong><em># Posting data to Google cloud</em></strong></pre><pre>bucket = client.get_bucket(&#39;yourbucket2&#39;)<br>object_name_in_gcs_bucket = bucket.blob(&#39;complete_df_&#39;+ time.strftime(&#39;%Y%m%d&#39;)+&#39;.csv&#39;)<br>df = pd.DataFrame(data=complete_df).to_csv(encoding=&quot;UTF-8&quot;)<br>object_name_in_gcs_bucket.upload_from_string(data=df)</pre><p>Flask Script</p><p>The flask script is used to build a web application that lets the user select one of the 30 stocks in the Dow Jones Index and returns the results from Google’s Big Query database. The returned result will show the date, stock, headline, sentiment, closing stock price, and volume of stock being traded.</p><pre><strong><em># Load Libraries </em></strong></pre><pre>from google.cloud import bigquery<br>import json<br></pre><pre><strong><em># Function to return data from Big Query Database </em></strong></pre><pre>def query_stackoverflow(stock):<br>    client = bigquery.Client.from_service_account_json(json_credentials_path=&#39;yourfile.json&#39;)<br>    query_job = client.query(<br>        &quot;&quot;&quot;<br>        SELECT * FROM `sunlit-inquiry-319400.ucsdcapstonedataset.StockData` WHERE name = &#39;&quot;&quot;&quot;+stock+&quot;&quot;&quot;&#39; LIMIT 1000<br>        &quot;&quot;&quot;<br>    )<br><br>    results = query_job.result()<br><br>    htmlmsg = &quot;&lt;html&gt;&lt;body&gt;&lt;table border=\&quot;1\&quot; style=\&quot;border-collapse:collapse;\&quot;&gt;&lt;tr&gt;&lt;td&gt;Date&lt;/td&gt;&lt;td&gt;Headline&lt;/td&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Sentiment&lt;/td&gt;&lt;td&gt;Close&lt;/td&gt;&lt;td&gt;Volume&lt;/td&gt;&lt;/tr&gt;&quot;<br>    for row in results:<br>        htmlmsg += &quot;&lt;tr&gt;&lt;td&gt;&quot; + str(row[2]) + &quot;&lt;/td&gt;&lt;td&gt;&quot; + str(row[3]) + &quot;&lt;/td&gt;&lt;td&gt;&quot; + str(row[4]) + &quot;&lt;/td&gt;&lt;td&gt;&quot; + str(row[9]) + &quot;&lt;/td&gt;&lt;td&gt;&quot; + str(row[13]) + &quot;&lt;/td&gt;&lt;td&gt;&quot; + str(row[15])+ &quot;&lt;/td&gt;&lt;/tr&gt;&quot;<br>    htmlmsg += &quot;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;&quot;<br><br>    return htmlmsg<br><br>from flask import Flask, render_template, request, jsonify<br>app = Flask(__name__)<br></pre><pre><strong><em>#</em></strong> <strong><em>Flask home page </em></strong></pre><pre>@app.route(&#39;/&#39;)<br>def home():<br>   return render_template(&#39;index.html&#39;)<br><br>@app.route(&#39;/songs&#39;, methods=[&#39;POST&#39;, &#39;GET&#39;])<br>def get_info():<br>    stock = request.form.get(&quot;stock&quot;)<br>    print(stock)<br>    return query_stackoverflow(stock)<br><br>if __name__ == &#39;__main__&#39;:<br>  app.run(host=&#39;0.0.0.0&#39;)<br></pre><p><strong>Docker¹¹</strong></p><p>Docker is a tool that makes it easier to create, deploy, and run applications by using containers¹². Containers package up an application with all of its necessary components, libraries, and dependencies and ship it all out as one package. <strong>Containers make it possible to run applications reliably on another computer’s environment.</strong> The following steps are required to build a docker container:</p><ol><li>Create a docker file which is the blueprint for building images</li><li>Build a docker image which the blueprint for the container</li><li>Run the container to see the output of the packaged product</li></ol><p>Docker takes over the responsibility of configuring the environment and standardizing the deployment pipeline. This allows for faster deployment and scaling time since the build only happens once during CI.</p><p>I turned all three scripts into their individual docker images and ran the docker containers locally to make sure everything was working as intended. Then each of the docker images were pushed to the Docker hub.</p><p><strong>Kubernetes¹³</strong></p><p>Kubernetes is a tool used to deploy and manage containerized web applications. First, a Kubernetes cluster is created, which is a set of nodes that run containerized applications. Then, under workloads, docker images are pulled from the docker hub and deployed as pods. A cron job was scheduled for Script one and Script two to run the ML pipeline on a daily basis and build our database over time. The Flask application was deployed and the user in real time could select one of 30 stocks from the Dow Jones and get returned its stock price and sentiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O80025yNdWnDL0hRnYlrcg.png" /><figcaption>Select a stock to see its stock price and sentiment of news headlines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCS7E7X7oj3aPSs1TqOfUQ.png" /><figcaption>Returned Data frame for Intel</figcaption></figure><p><strong>Summary</strong></p><p>To summarize how we developed an end to end ML pipeline and deployed it into production: we started with our problem statement of trying to build a sentiment classifier that would determine the polarity of news headlines. We compared the performance of three models and went with Google’s XLNet model after we fine tuned it on the Financial Phrase-Bank dataset. Then we converted our Jupyter notebooks into Python Scripts and built Docker images and pushed them to the Docker Hub. Finally, we used Kubernetes to deploy and manage our containers.</p><p><strong>How to use this to make better informed investment decisions &amp; further exploration</strong></p><p>Algorithmic trading is a difficult task because so many different variables are involved in the real world. Positive and negative sentiments from media releases have a substantial impact on the stock price of a company. Stock price prediction is very complex and volatile and has been an interesting and dynamic field of research. Data is becoming increasingly voluminous and crucial to all businesses, manual analysis is no longer feasible in today’s fast moving world. Most traders get their information from news, which makes it an influential factor in forecasting change in the stock market. Using a ML model like this in real time to track sentiment for a stock, the volume of shares being traded, and taking into account historical stock prices can lead to a sharpe ratio greater than 2.0¹⁴.</p><p><strong>Where the Real Magic Lies — Reinforcement Learning</strong></p><p>If I had more time I would have loved to build upon this work and utilize reinforcement learning and train a bot to trade stocks based on time series data, sentiment data, and knowledge graphs. I have put a research paper in references that was able to achieve a sharpe ratio greater than 2.0¹⁴. If interested in building upon please refer to my Github, and I would recommend using Open AI’s gym toolkit library¹⁵. Please reach out to me on LinkedIn if you have any questions. Cheers!</p><p><strong>References</strong></p><ol><li><a href="https://www.cnbc.com/2021/02/01/gamestop-shares-reddit-trader-frenzy-continues-into-february.html">https://www.cnbc.com/2021/02/01/gamestop-shares-reddit-trader-frenzy-continues-into-february.html</a></li><li><a href="https://www.ibm.com/cloud/learn/machine-learning">https://www.ibm.com/cloud/learn/machine-learning</a></li><li><a href="https://www.ibm.com/cloud/learn/natural-language-processing">https://www.ibm.com/cloud/learn/natural-language-processing</a></li><li><a href="https://huggingface.co/datasets/financial_phrasebank">https://huggingface.co/datasets/financial_phrasebank</a></li><li><a href="https://www.researchgate.net/publication/275828927_VADER_A_Parsimonious_Rule-based_Model_for_Sentiment_Analysis_of_Social_Media_Text">https://www.researchgate.net/publication/275828927_VADER_A_Parsimonious_Rule-based_Model_for_Sentiment_Analysis_of_Social_Media_Text</a></li><li><a href="https://ai.googleblog.com/2018/11/open-sourcing-bert-state-of-art-pre.html">https://ai.googleblog.com/2018/11/open-sourcing-bert-state-of-art-pre.html</a></li><li><a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a></li><li><a href="https://www.borealisai.com/en/blog/understanding-xlnet/">https://www.borealisai.com/en/blog/understanding-xlnet/</a></li><li><a href="https://github.com/Shivampanwar/Bert-text-classification">https://github.com/Shivampanwar/Bert-text-classification</a></li><li><a href="https://arxiv.org/pdf/1906.08237.pdf">https://arxiv.org/pdf/1906.08237.pdf</a></li><li><a href="https://docs.docker.com/get-started/">https://docs.docker.com/get-started/</a></li><li><a href="https://towardsdatascience.com/deploy-machine-learning-pipeline-on-cloud-using-docker-container-bec64458dc01">https://towardsdatascience.com/deploy-machine-learning-pipeline-on-cloud-using-docker-container-bec64458dc01</a></li><li><a href="https://kubernetes.io/">https://kubernetes.io/</a></li><li><a href="https://arxiv.org/pdf/2001.09403.pdf">https://arxiv.org/pdf/2001.09403.pdf</a></li><li><a href="https://gym.openai.com/">https://gym.openai.com/</a></li><li><a href="https://imgur.com/gallery/ymJEdr2">https://imgur.com/gallery/ymJEdr2</a></li><li><a href="https://github.com/Aditya-Bahl/UCSD_Machine_Learning_Engineering/tree/main/Capstone">https://github.com/Aditya-Bahl/UCSD_Machine_Learning_Engineering/tree/main/Capstone</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=347f5fad0fcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>