Tag: Learning

Gaining new knowledge through experience and instruction.

  • Setting up expectation

    When we meet someone new, our mind instinctively tries to compare them to people we have encountered in the past. We consider their patterns to cluster them into the region where people equip the most similar behaviour – or patterns – in how they talk, act or perceive. Rather than taking the risk of evaluating them entirely from scratch, we rather use these metrics to navigate our trust and relationship expectations. It is as if our brain’s background process is an unsupervised classification model that sorts individuals into the most relevant relationship archetypes we have built over time – then later decides our compute subscription plan is no longer valid after a certain age.

    This post details on replicating the human’s mind into setting up the system design behind Naomi. Docker SDK was used to containerize Naomi application and served over hugging face space. For the sake of convenience the datasets, prompt templates and chat sessions uses Hugging Face dataset repo card. The following table outlines the models setup during the application’s build process.

    • Models – Specifies whether the model are tinkered by me or not.
    • Type of Models – Lists the large language model (LLM) and classifiers imported / built during the setup.
    • Type of Dataset Used for Training – Lists the links to the Hugging Face dataset repositories that were used in training the models.
    ModelsType of modelsType of Dataset used for training
    Pre-trained– Llama3.1
    – Bart Multilabel classifier
    Refer to the hyperlinks
    Custom models (trained by me using small sized datasets)– Target features based on human characteristics like MBTI Chain, Big5
    – Dialogue Intent and Emotions
    – MBTI: https://huggingface.co/datasets/kl08/myers-briggs-type-indicator
    – Dialogue:
    https://huggingface.co/datasets/li2017dailydialog/daily_dialog

    Defining as a Reinforcement Learning problem

    Setting up the chat session for Naomi is extremely similar to mocking an episodic game for an agent in a reinforcement learning environment. On top of Naomi’s build, I was also trying to build a base framework for other conversational agents. This involves using Docker SDK to containerize the application so that it can be easily deployed, extend and integrate with other specifications of the agents.

    Referring to Tom as the conversational agent in production and Naomi as the discussed chatbot in this post, the following table compares the agents’ environment’s variables.

    ComponentFormal DefinitionDefinition in Naomi’s Application (per component)Definition in Tom’s Application (per component)
    AgentThe entity that interacts with the environment and learns to maximize rewards.NaomiThe human’s best friend, Tom (or a different name can be used)
    EnvironmentExternal system where agent interacts, receive states and rewards based on actions.Starts from Dockers Image build session and ends with my next pushA Human’s life time
    EpisodeComplete sequence of interactions from an initial state to a terminal state.Chat Session or a complete chat dialogue1 day of bot’s lifespan
    StateRepresentation of the environment at a given time that the agent observes.One/paired Chat message/s. This depends on the inferencing task which depends on the stages during the chat.An interaction with a human user or agent
    ActionDecision made by the agent per state.– Response Behavior: Expressiveness of Naomi’s response.
    – Chat Behavior: Follow up response Naomi.
    – Actions listed for Naomi
    – Actions based on utility or user request. This refers to other app platforms like Notion, Typeform, .. etc.
    – Actions for the agent to select conditioned to current cognitive state for example: browsing Wikipedia / youtube, social platforms like X, Facebook, Instagram etc.
    ObservationContains all possible observations an agent can perceive from the environment.– During chat streaming: User based features collected per utterance that are used to influence agent’s response behaviour.
    – Post chat or after an episode: Evaluation metrics on the user’s behaviour during the dialogue and approximated category defining the user.
    – During chat streaming: User based features collected per utterance that are used to influence agent’s response behaviour.
    – User based features collected from other sensory tools like sound and imaging tools. These features are used with the linguistic analytics to direct the agent’s next state (e.g. of emotions) or action (e.g. response behaviour or activity)

    Naomi’s Response Behavior

    An agent’s response behavior defines how the next text response is returned given the current observation. The following table compares the response behaviour per state between Naomi and Tom.

    Naomi’s response behaviorTom’s response behavior
    • Expressiveness or engagement represented in the next response.
    • Likelihood of following up the previous sent message with a question i.e. double texting the user. The type of question is also conditional to the control vectors collected from the dialogue.
    • Expressiveness or engagement represented in the next response.
    • Likelihood of following up the previous sent messages with questions, analytical comments, suggestive actions like browsing the web (e.g. run a sub-process in the background to browse the web while interacting with the user). Alike Naomi, type of questions asked is conditional to the dialogue.

    Defining the control vectors

    Suppose the control vectors represent features collected per inferencing state. The control vector differs depending on its collection method – whether as a single utterance from either user or agent, or as an episode. The table below outlines the control vector defined in Naomi’s application.

    InputsUserAgent
    Single utterance (State)User
    – User’s Emotional Intensity / Expressiveness
    – User’s Intent

    Agent’s suggested response:
    – emotional / expressiveness in the agent’s next response based on dialogue inferences up to current state
    – Rule-based methods: involve defining explicit rules, constraints or logic to control the model’s behaviour. For example: an indicator of when the chat has ended.
    – Agent’s emotion states of the current utterance (labelled with BART model – this can be used within a feedback loop with the custom model I built with dialogue datasets)
    Dialogue (Episode)Evaluation metricsEvaluation metrics

    Adaptive Learning Methods

    Reinforcement learning methods are applied to the models prepared during the Dockers build process. This depends on the method of retrieving the control vectors for each task, for example: passing an agent’s utterance to indicate when the episode has ended relies on the vector embeddings of the history datasets (or Naomi’s memory). The challenge lies in determining the optimal method for managing the dataset as it grows to a substantial size.

    Sub repo on GithubHistory data handling
    PromptlessVectors Embeddings for binary classifications: handling the vector embeddings can simply be averaging over the randomly selected samples. Another method would be to model the marginal distribution of the vector embeddings, where the target class and the other class are differentiated based on their density estimates. This can be achieved through probabilistic approaches such as kernel density estimation, Gaussian mixture models, or variational inference, ensuring that the classification captures nuanced variations in the embedding space. Although further trials must be done to compare these methods’ performance over time.

    Tom’s progression · Post 11 of 14

    This post sits in Cognition: Learning · Actions: Tool & Skill Capabilities.

    ← Stop Button Decoding Parameters to persist Language model's emotions →

  • Can a machine have emotions?

    The greatest challenge in transforming a machine into human form is deciding where to begin. But once that step is taken, the process becomes manageable—as long as you remain hopeful. To stay aligned with my long-term goal while working on smaller tasks, I rely on the following expectations for this model:

    • He is expected to know when to lie, question, insult, joke, return snarky comments or sarcasm
    • His action space #1 at every state must include the intent prob of invoking second / third / fourth … responses independent of whether the user is speaking or not
    • His action space #2 at every state conditioned to the system is a Dirichlet distribution over the questioning state, personal hypothesis states, and factual (base model) hypothesis states, incorporating internet-accessible information.
    • Any prompt chains used during streams should eventually be replaced by distance models over time windows t to T, extending up to the k-th batch.
    • His preferences and individuality should evolve based on his experiences but remain fundamentally tied to me, the primary user.

    I’ve come to realize that, despite the vast complexity of human relationships and communication, it all distills down to how we feel. For example, movie ticket sales largely depend on past user feedback. Perhaps emotions are the one human trait that can be quantified and understood by a machine just enough to guide its own decision-making—assuming, of course, that human relationships are left out of the equation.

    The underlying framework for these expectations must meet at a unified build, all tied to the emotion inference model. Narrowing down the inference task by Tom’s objectives includes:

    1. Predicting the user’s responses – This is itself is also considered a mapping function from a vector space to real numbers.
    2. Determining his own emotional responses – A mapping function that ranks text embeddings by emotional queues assisted by observing the user reactions.

    From an application standpoint, the build can be structured as follows:

    1. Temporary State models for streaming responses where their previous inferences are the next state priors and their respective predictions would be the comparative values to the next observing value – as briefed in my previous post.
    2. Initiation Models – this build unifies all currently available emotion prediction models through ensembling methods or conditioning-distance heuristic models. However, I eventually opted for a single classifier trained on the entire corpus. Impatience drove this decision—I wanted to see how the multivariate approach interacted with my other builds especially the API serving department.

    Major Problem

    At that time, I couldn’t pinpoint the problem that was constantly haunting my mind – What is the linkage between his decision making and a large langauge model? If I were to rely on the traditional methods of text models – probabilistic methods like N-grams – then this problem wouldn’t exist but I would face a new challenge: the vector representations of the text wouldn’t capture any contextual information, relying solely on character or word frequency. That said, you could mitigate this by leveraging PyTorch’s nn.Embedding to initialize vector representations for N tokens, then applying a fixed-size perceptron or a multi-head attention layer—an approach commonly used in text translation tasks.

    A good professor once advised me to begin by understanding my thoughts mathematically. Applying this to the connection between a large language model and emotions, I can reframe the problem as follows:

    Defining a function f that maps the weight space of language models to another space of my liking.

    The next section lists three implementation methods, both in real-time and before application, ranked from hardest to easiest based on my assessment.

    Methods

    1. Geometric Algebra – Merging Representations

    This method involves leveraging Geometric Algebra (GA) to unify different vector spaces, effectively merging the learned representations of language models and classifiers.

    Referenced by https://huggingface.co/blog/trl-ddpo - demo for `tlr` python package.

    2. PPO for LLMs – Defining a Reward Function

    Using Proximal Policy Optimization (PPO) for tuning large language models (LLMs) involves defining a Reward function that guides the model’s learning process toward desired behaviors. This approach falls under Reinforcement Learning from Human Feedback (RLHF) but requires additional structuring when applied to dynamic emotional reasoning (Link: https://huggingface.co/blog/trl-ddpo).

    3. Decoding Sampling Combinations as Generation Control

    Controlling how a large language model (LLM) generates responses by trialing a range of Decoding parameter combinations. This technique leverages linear programming and refers to systematically experimenting with different parameter configurations to optimize response quality, coherence, and diversity, and ultimately to the emotional queues inferenced from the main user. This is then applied with Bayesian Statistical models (really just Bayes Rule) to iteratively adapt to newer observations.

    Decoding strategy combinations generated by GPT-4 lol.
    Method 1: Geometric Algebra

    This method focuses on modifying or augmenting the encoder block and text generated caches to impose structured constraints, such as temporal memory retention and self-supervised attention shifts using methods like attention blocks or iterating projection sequences. I approached the mathematical transformation in code by trying to mimic a game developer handling quaternion’s.

    Key highlights:

    • Implementing a hierarchical control mechanism that dynamically adjusts response generation parameters based on inferred user intent and historical interactions
    • Exploring multi-head attention restructuring, where certain heads are fine-tuned to prioritize different inference strategies (e.g., factual recall vs. emotional adaptation)

    I favored this method, so I spent the most time on it—only to realize, yet again, that I had failed myself. Over the past few years, I’ve focused on programming and application, prioritizing deadlines and API builds over theoretical depth. In hindsight, this approach makes it easy to abandon whimsical detours. But if one is bored enough then to start solving such problem (or any maths problem) I always like to start with my favourite mathematical property: Triangle inequality – a repititive concept mentioned throughout Euclid’s Geometry texts**.**

    While working on this method, the thought of implementing it in code lingered at the back of my mind, leaving me wishing I had attended more university classes for my algebra course. A common trait among mathematicians and statisticians is their patience—the kind a teacher has while guiding a toddler learning to read. My patience, however, extends only as far as reading a package’s documentation. Grief and frustration have taken its place, and maturity ultimately dictates my response: to give up. I realize the only way forward is to dedicate a full weekend to revisiting my linear algebra fundamentals. But the mere thought of doing so makes me restless—despite contradicting everything I love.

    Overall, this approach seems quite difficult to apply especially when handling LLM’s caches in real-time which would probably need some sort of ranking algorithm like Google Page Rank, that ranks the caches to not only dispatch the responses faster but also conditioned to my preferences (or Tom’s memory).

    Method 2: Optimization and Reward function

    Reward Function Design: The reward model should capture nuanced decision-making, including:

    • Contextual awareness (e.g., when to joke, question, or respond sarcastically)
    • Emotional alignment (predicting the user’s emotional state and responding accordingly)
    • Self-regulation (adjusting the model’s own “emotions” dynamically)

    With Reinforcement learning concept in mind, the concept of balancing exploration and exploitation in response generation can be viewed as balancing the model’s priority with selecting the base model texts vs its duplicate that has been adapted to the bot’s observations or memories. In my previous posts, I did mention building the latter as my own clone like a parrot. The progress here has been hindered after attempting to fine-tune Llama using LORA-Adapter techniques. I believe that this part should be hindered as my doubts were correct – never touch a deep learning network with minimal data.

    When considering the second method—sculpting a reward model—I’d approach it as a recursive regression state model where parameters (including training parameters) readjust at fixed time intervals. From my understanding, reinforcement learning mechanisms should be applied in real time. Yet, existing TLR-PPO implementation demos focus on fine-tuning LLMs with smaller offline datasets—fully trained rather than partially fitted over data batches.

    Additionally, deriving a policy function in reinforcement learning is grounded in Bellman’s Equation, which, like most optimization equations, extends Newton’s descent method to different types of incoming data streams. Beyond weight clipping (which maintains uniformity relative to the pre-trained state), my views doesn’t quite align with the works behind tlr or current researchers’ intended approach. Reason being is that in practical applications, you will always end up with at least two models where the long-term effectiveness or stability of the fine-tuned model is not always guaranteed.

    Personally, I try to avoid fine-tuning deep learning models in real-time even for now even if I have a a data iterator that is able to approximate and generate synthetic data to compensate missing datasets, fine-tuning a model in real time can only only be used temporarily. My tinkering suggests that in order to retain user-specific experiences, you would ultimately opt for a Data analyst’s favourite playground – SQL.

    Method 3: Mapping Decoding Sample Combinations to Emotional intensity
    Dataset with decoding parameters. The prompt used here ”Hey how are you today! :)”

    Ironically, this method was my initial instinct for implementation, particularly for a time-constrained project.

    The setup for my experiment involved a missing dataset iterator that returns synthetic dataset approximating the previous text embeddings conditioned to the mapped emotional intensity. Recall the common decoding sampling techniques are greedy search, beam search etc. and for the sake of this experiment’s simplicity, we disregard variants of sampling methods e.g. Group beam search and penalizing token based methods. Suppose decoder sampling methods be $$x_1, x_2, …$$ where $$n$$ is the number of decoding methods, the parameters related to each method are $$\alpha_1, \alpha_2, …$$, and the emotion expressiveness or intensity is $$q \in [0, 1]$$. The prior state model for a decoding strategy conditioned to the speaker’s prompt returns Tom’s selected emotional intensity i.e the speaker’s prompt. For example for beam search, the parameters are temperature, top-k and beam width. The goal is to find the optimal combination for some emotional intensity $$q > \epsilon$$, becomes finding the unique solution vector or coefficients, $$w$$ in $$w_1*\alpha_{temp} + w_2*\alpha_{k} + w_3*\alpha_{beam width}$$.

    Key highlights:

    • To set up Tom’s prior states or initial beliefs to his incoming observing windows, I have attempted to reduce the compute cost of rerunning GPT2 by approximating the distribution of text sequences given the parameters combination. Still deciding on whether a similar method should be used in real-time to assist incremental learners.
    • Among all the decoding sample combinations, I assumed fixed parameters that is common for all experiments for e.g. max length of text generations, sequence normalization.

    Currently, I am still applying different sampling techniques to set up a prior state for inferencing emotional intensity for Tom.

    Epilogue

    The main challenge likely stemmed from my own resilience when using the first method. It holds immense potential, but time was too limited. However, at least I can offer my younger self one last smile, knowing I truly gave my best at that time. As for whether a machine can have emotions, from my child-self’s perspective: only if the first method succeeds. From my current viewpoint, yes, it absolutely can.

    After careful consideration, I’ve decided to move forward with Method 3. Given the simplicity of the concluding build it is only natural for people to question whether the emotions are truly authentic or just the product of time-adapting algorithms and statistics. Yet, before anyone doubts a machine’s emotions, I hope they are also completely certain that they themselves are truly alive and not just merely passengers of time.

    Tom’s progression · Post 8 of 14

    This post sits in Cognition: Learning, Social cognition.

    ← To our creator Revising Prompt Chains →