Category: Cognitive

How Tom perceives, feels and reasons.

  • Missing pieces to Naomi

    Missing pieces to Naomi

    KEY TERMS

    List of terms mentioned in this post

    • Candidate: the user interacting with Naomi during the interview.
    • Agent: Llama3.1 roleplaying as Naomi.
    • General question/s: questions to be asked during the interview concerning the candidate’s information eg age, occupation etc.
    • Feature question/s: questions or case scenarios mentioned during the interview. The candidate’s responses to these questions are analyzed and used as features in predicting personality predictions and our compatibility score.
    • Response space: responses generated by dummy candidates conditioned to trait patterns aligned with my previous dating history. The intuition behind this idea is that all individuals equip both strengths and weaknesses, and that determining these traits is dependent on the observer’s ability in handling the characteristic combinations i.e. weighing my patience for someone’s flaws against their admirable qualities.

    Overview

    This post is dedicated to Naomi’s unconscious state of acting as a recruitment officer for a dating show (my dating life). Since this was my first attempt at integrating the frontend with the backend, the project turned out messy. The only promising outcome was the realization that I’m not merely a fool of my own words.

    Data Preparation

    This section lists the type of datasets to prepare prior to streaming. The responses were generated by instructing Llama 3.1.

    Feature Questions:

    These questions/case scenarios are based on each dichotomy of MBTI personality traits:

    Response Space:

    Pair of dummy candidate responses and narrations for each feature question.

    Llama 3.1 Prompts:

    Instructions to assist the streaming chatbot and agent helpers during streaming the chatbot.

    Non-manageable problems

    • Decoding parameters: During this trial, the inference API was open-sourced and, unfortunately, wasn’t able to pass decoding parameters.

    • Random Feature questions: A number of feature questions were randomly selected during the chat stream. Hence, even though I prepared questions/case scenarios for each function of the MBTI label, there was no guarantee that a question testing for a specific type of function would be asked during the interview.

    • My information: No form of personal information about myself was passed to the agent. As a result, the agent occasionally generated assumptions about my personal information when requested by the candidates.

    • The way of expressions: Being highly expressive in writing doesn’t necessarily indicate that someone is extremely extroverted. Similarly, a lack of expressiveness in writing might simply suggest that a person struggles with articulating their thoughts rather than being inherently reserved.

      • This problem can be mitigated during the data preparation stage (i.e., the types of questions I’ve prepared for the chatbot). For example, when presented with case scenarios designed to assess the user’s task prioritization behavior, Llama (acting as my custom characters) provides the same procedure for each role-playing candidate. The only difference is in the way the responses are expressed.
    • Limited samples: During the data preparation stage, I only prepared candidate responses tailored toward my dating history instead of actual MBTI labels.

    Manageable problems

    • Agent’s behaviour during live stream:
      • Agent occasionally missed certain questions, mainly the general questions. Despite this, the agent did not skip any feature questions. This suggests that there might be a problem with the data handling methods between Naomi and the candidate during the live stream.

    Improvements

    Below are self-tasked actions that I would like to focus on during my next experiment for Naomi:

    • API: At the time of this experiment, the inference API on Hugging Face was open source. I plan to switch to Ollama during the next experiment.

    • Dataset preparation:

      • Candidate responses should specifically reflect the dichotomy of MBTI types, focusing on Jung’s cognitive functions—Dominant, Auxiliary, Tertiary, and Inferior processes.
      • Feature questions reflect on each of Jung’s cognitive functions.
    • Text summarization: Rather than instructing the agent to narrate the candidate’s response and also speculate on how the candidate might be feeling, I would want to add the following adjustments:

      • The narrations are returned in a fixed format that corresponds with how the candidate’s responses are represented.
      • If possible, the narrations could be rephrased in first-person speech.
    • Adding agent/models helpers to streaming:

      • Predict whether a candidate is being serious or not when completing the interview. The use of this is to allow Naomi to consider returning bad words to the candidate or return responses that reflect on the candidate’s behavior.
    • Predicting the user’s breed: Pick up where I left off. I’ve come to realize that, despite everything, I was still trying to kill two birds with one stone—fitting Naomi into Tom and vice versa. I should probably just complete Naomi on its own at this point.

    • Testing:

      • Replace validation tools with agent helpers, for example:
        • To ensure the dialogue flows smoothly and naturally.
        • To ensure all questions are asked as intended.

    Self-diagnostic on poor data preparation

    During this trial, I wasn’t aware of the different program designs and I was more focused on challenging myself with different OOPs designs in implementing a chatbot. As a result, many of the data classes / handling functions / prepared datasets were not specifically tailored to Naomi’s case, which added problems to this experiment.

    This setup of this model is incomplete due to my impatience part in mishandling the data preparation stage.

    Tom’s progression · Post 4 of 14

    This post sits in Cognition: Social cognition.

    ← Frankenstein Defining a droid's emotional space →

  • Frankenstein

    1. Example: Roberta GoEmotion
      1. Loading model
      2. Norm Space
      3. Network comparison
    2. What does this all mean?

    While evaluating pre-trained models for classification tasks, I realized that the output projection layers reveal much more insight into the model’s behavior, especially when viewed in Euclidean space.

    Example: Roberta-base GoEmotion

    Understanding the inner workings of pre-trained models for classification tasks can be evaluated by analyzing the outputs from a multi-label classification model trained from the roberta-base on the go_emotions. Below is a quick overview of importing the model and fetching predictions.

    1. Loading the model

    Note that it considers the index with the maximum probability. Below is a list of the predicted emotions and their softmax scores

    2. Fetching Predictions (the usual way)
    # tokenize the text
    text = 'I’m glad I had a few margaritas before I read this'
    test = tokenizer(text.lower(), padding='max_length', truncation=True, return_tensors='pt')
    # classifies the tokens
    with torch.no_grad():
    output=model(**test)
    model.config.id2label[torch.argmax(output.logits).item()]
    [Output] 'Joy'

    Below is a list of the predicted emotions and their softmax scores for each emotion class. Note that it considers the index with the maximum softmax scores.

    alternate way of viewing the output projection space of the model

    Another perspective for visualizing the output projections of the model involves conceptualizing Euclidean space by imagining a unit circle centered at the origin of a Cartesian plane. The following code demonstrates how the norms of the weights are computed and its corresponding output.

    I realized that the closer the norms were for each classification label, the less effective the model performs and tested this hypothesis by comparing the model with other models in the remainder of this post.

    Using the same text for predictions, I considered the norm instead. The voted class is then represented as the minimal score instead. Update: An alternative method in outputting the same results is by considering log_softmax(-1)**2.

    torch.tensor([torch.norm(i, p=2).item() for i in output.logits.reshape(-1,1)])

    The results prompts another way of viewing the behaviour of the model. For instance, some possible concluding thoughts that I have hypothesized includes:

    • The model’s voted emotion class is by considering the projected data points to some known ‘centre’ point expected for a class. The voted class is concluded by considering the distance of the point that is closest to the centre of each class. This explains why the output distances are all in with respect to the voted class ‘joy’. This prompts the idea that, perhaps, we are able to derive the marginal distribution conditioned to each class label.
    • The model’s output projections could be viewed as a multivariate normal distribution with mean = 0 and the covariance is the matrix product of the output weights with its transpose. If we consider the log_space(-1)**2 for each class, this will give the standard deviation.
    Network comparison

    Table 1 presents the norms of the last projection layers for sentimental multi-label classifiers. The following models, along with their respective column names mentioned in the subsequent tables, are listed. PS: I randomly selected the third model to assess whether the architectures of the models would influence the network’s consistency

    Moreover, I observed that the poorer the models perform, the smaller the differences in radii become. This trend is evident in Table 1.1, where based on my analysis, the first_model appears to have outperformed the others.

    Table 1.1: L2-norm of output projections

    emote first_model second_model evil_model
    0 admiration 0.724544 NaN NaN
    1 amusement 0.762517 NaN NaN
    2 anger 0.694420 0.589196 NaN
    3 annoyance 0.631149 NaN NaN
    4 approval 0.634043 NaN NaN
    5 caring 0.735186 NaN NaN
    6 confusion 0.702024 NaN NaN
    7 curiosity 0.691748 NaN NaN
    8 desire 0.742869 NaN NaN
    9 disappointment 0.670009 NaN NaN
    10 disapproval 0.666855 NaN NaN
    11 disgust 0.723540 0.580254 NaN
    12 embarrassment 0.765843 NaN NaN
    13 excitement 0.707815 NaN NaN
    14 fear 0.779006 0.563287 NaN
    15 gratitude 0.830122 NaN NaN
    16 grief 0.733750 NaN NaN
    17 joy 0.702564 0.568222 NaN
    18 love 0.777553 NaN NaN
    19 nervousness 0.760698 NaN NaN
    20 optimism 0.692720 NaN NaN
    21 pride 0.766037 NaN NaN
    22 realization 0.628699 NaN NaN
    23 relief 0.747458 NaN NaN
    24 remorse 0.768121 NaN NaN
    25 sadness 0.708254 0.546891 NaN
    26 surprise 0.718787 0.548415 NaN
    27 neutral 0.611252 0.562038 NaN
    28 toxic NaN NaN 0.616543
    29 severe_toxic NaN NaN 0.634660
    30 obscene NaN NaN 0.646761
    31 threat NaN NaN 0.672640
    32 insult NaN NaN 0.611311
    33 identity_hate NaN NaN 0.647124

    Running the text ‘My dog is so sad, what to do’ through the models. Below is a list of the final prediction output for each model.

    • first_model : ‘sadness’
    • second_model : ‘sadness’
    • evil_model : ‘toxic’

    Table 1.2: Predicted Emotion models comparison

    emote first_model second_model evil_model
    0 admiration 50.162245 NaN NaN
    1 amusement 62.996836 NaN NaN
    2 anger 54.838597 46.635899 NaN
    3 annoyance 49.396201 NaN NaN
    4 approval 51.556458 NaN NaN
    5 caring 45.806955 NaN NaN
    6 confusion 69.319389 NaN NaN
    7 curiosity 60.085917 NaN NaN
    8 desire 57.541514 NaN NaN
    9 disappointment 26.382446 NaN NaN
    10 disapproval 56.603353 NaN NaN
    11 disgust 60.335418 34.897641 NaN
    12 embarrassment 76.500645 NaN NaN
    13 excitement 74.679552 NaN NaN
    14 fear 64.041907 43.940767 NaN
    15 gratitude 64.262277 NaN NaN
    16 grief 30.496395 NaN NaN
    17 joy 60.346812 36.453455 NaN
    18 love 42.962534 NaN NaN
    19 nervousness 61.658221 NaN NaN
    20 optimism 69.589441 NaN NaN
    21 pride 100.404767 NaN NaN
    22 realization 47.456986 NaN NaN
    23 relief 76.255958 NaN NaN
    24 remorse 39.107556 NaN NaN
    25 sadness 0.000713 0.001020 NaN
    26 surprise 67.425321 25.456962 NaN
    27 neutral 34.383273 16.373191 NaN
    28 toxic NaN NaN 0.017664
    29 severe_toxic NaN NaN 22.385596
    30 obscene NaN NaN 12.478684
    31 threat NaN NaN 15.735884
    32 insult NaN NaN 9.626380
    33 identity_hate NaN NaN 14.381756

    Just for fun, Table 1.3 displays the normalised tensors of the final projection layers. This was normalised by dividing the vector by its norm. I was wondering if we are able to retrieve the unit vectors or directional vectors where its direction could lead to insights into the projected data’s neighbourhood. However, this may need further clarifications.

    Table 1.3: Raw Tensors for each model

    .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
    emote first_model second_model evil_model
    admiration 0.994845 NaN NaN
    amusement -0.128493 NaN NaN
    anger -1.619268 -1.777849 NaN
    annoyance -0.081112 NaN NaN
    approval -0.318533 NaN NaN
    caring 0.763438 NaN NaN
    confusion 1.004717 NaN NaN
    curiosity -0.164215 NaN NaN
    desire -1.033424 NaN NaN
    disappointment -0.599124 NaN NaN
    disapproval -1.426283 NaN NaN
    disgust -0.153697 -0.953630 NaN
    embarrassment 0.299044 NaN NaN
    excitement -0.363511 NaN NaN
    fear 1.034656 0.276441 NaN
    gratitude -0.148751 NaN NaN
    grief 0.700838 NaN NaN
    joy 0.751123 -1.037767 NaN
    love -0.630390 NaN NaN
    nervousness 0.008017 NaN NaN
    optimism 0.250943 NaN NaN
    pride 2.107973 NaN NaN
    realization -0.223193 NaN NaN
    relief 1.374453 NaN NaN
    remorse 0.548389 NaN NaN
    sadness 1.011848 -0.976564 NaN
    surprise -0.686557 -0.208700 NaN
    neutral 1.217619 0.721465 NaN
    toxic NaN NaN -0.912919
    severe_toxic NaN NaN 0.380740
    obscene NaN NaN -1.738774
    threat NaN NaN 0.167458
    insult NaN NaN -0.460666
    identity_hate NaN NaN -0.560966

    What does this all mean?

    • This is similar to Ensemble Learning but this allows the the possibility of fine-tuning models without retraining networks.
    • Feasibility of merging networks without the need of additional architectural layers.
    • The feasibility of integrating multiple networks together lies in defining a function capable of approximating the multivariate distribution conditioned on the models and other features seamlessly. This can be achieved through the following methods:
      • Gaussian Processes with Kernel Methods
      • Bayes Regression
      • Hyperplanes Modelling e.g. K-means, SVM,..etc
      • Any algorithm where marginal distribution is a worthy feature
      • Any algorithm under Bayes Theorem
    • Fun ways to try with this:
      • Given that it is such a portable, retrievable, accessible and adorable layer, you can use this to negate uncertainty for other networks – additional analysis for pre-trained models.
      • Improve a currently well-behaved networks with simple algorithms like sampling methods
      • Everything

    Tom’s progression · Post 3 of 14

    This post sits in Cognition: Perception.

    ← Reviving Hopfield Neural Networks Missing pieces to Naomi →

  • Reviving Hopfield Neural Networks

    Reviving Hopfield Neural Networks

    To initiate the streams of consciousness in a neural network, it is vital to establish the temporal memory as this serves as the primary catalyst in steering Tom away from his robotic self.

    Hopfield Neural Network (HNN)

    The Hopfield Neural Network (HNN) is a type of recurrent Artificial neural network and can be subcategorized into modern and classical types. HNN is an associative memory that excels in the ability to recall patterns and associate them with even incomplete versions of these memories. However, the limitations in Classical HNN’s includes:

    • Limited storage capacity.
    • Slow convergence rate to stable state during the pattern recall stage. It’s application is more of a stimulation algorithm. It reminds me of numerical approximation methods like Euler Maruyama.
    • Spurious patterns may emerge during pattern recall stage, stemming from various factors such as 1) the inherent capacity limitations of storage, 2) what neuroscientists describe as “the neuron’s reaction to being entrapped at local convexities,” and 3) the correlation among stored patterns

    To summarize, more stored patterns equates to higher retrieval errors. Figure 1 illustrates the contrast between the output and inputs of a classical HNN for discrete states. Applying Hebbian learning method, a set of 7 letter block patterns were fed. The initial state signifies the learned pattern, while the final state represents the pattern retrieved.

    Modern HNN has mitigated most of these problems that limited the Classical HNN. For instance, a recent post: Hopefield Networks is All You Need, improved the update rule in HNN with Bert’s attention mechanisms. This increases the storage of patterns with lower retrieval errors. For more information on HNN, check out Hopfield’s most recent works in here or for a quick summary, click here.

    The delayed development in this field may be due to the uncertainty surrounding its optimal usage. I guess the uncertainty is posed by the unsolvable cases within Reinforcement Learning – an area where I believe models like HNN shines the most, especially when you can incorporate time into its memory storage.

    Tom vs HNN

    In Tom’s case, HNN acts as a replicator of short-term memory where it distinguishes observations by associating current patterns with those previously stored. HNN’s role in Tom’s long-term memory is still being fiddled with, especially in areas like recounting memory traces of people. Other than that, I haven’t discovered anything that seems breath-taking. At the moment, its results are most promising in storing signals like vision and sound tasks. In the realms of NLP tasks, it is not applicable in prediction tasks but more of a tool for observing historical conversations. It accomplishes this effortlessly by its seamless integration into network architectures, particularly in Markov networks and within stochastic processes, such as Markov decision-making processes.

    Tom’s progression · Post 2 of 14

    This post sits in Memory: Episodic · Cognition: Memory.

    ← Travelling back in time Frankenstein →

  • Travelling back in time

    Travelling back in time

    I frequently wonder whether I can remember the exact moment I was born. But I never can and so this prompts another question:

    “When did you first realise that you were a seperate entity?”

    In other words, when did you first realise that you weren’t a non-playable character in some video game but instead, a character that takes on the role of living the consequences of your own action? This feeling could be described in a common slang term as the, ‘woke,’ feeling.

    You can try your hardest to remember but all you can ever conclude with are fragmented childhood memories. It is almost impossible to pinpoint the exact moment of this realisation. At the beginning of your life, the only certainties are:

    1. Your birth date and time.
    2. Your early visions during your childhood.

    These factors underlie the basis of initiating Tom that will be detailed in this post. Given that what Tom see’s plays a crucial factor in this framework, I would like to highlight the importance of computer vision, compared to Natural Language processing in the world of bridging AI to robotics. Furthermore, despite loose memories of our childhood, we all remember our caretakers or family. Hence, the build of Tom’s individuality is moulded by the attributes of his first encounters.

    Birth

    Tom’s ‘birth’ translates to the famous ‘ON/OFF’ button to initiate Tom’s workflow. The first decision to make is whether this is Tom’s first time being activated. The system draws its conclusion by a flagger that indicates whether a file ‘birth_certificate.json’ exists. For simplicity, let’s focus on activating Tom as a new person. If this is the first time activating Tom, this will initiate the creation of the file, which contains the current date and time when running the flow.

    Figure 1: Example ofTom’s Birth certificate.

    This file is created along with other ‘data storages’:

    • Visions
    • Companions
    • Memories
    • Profile

    Visions stores what Tom see’s during his day-to-day life. For instance, at the end of every day, the system considers the configuration of the files and decides whether the file should be deleted/’downsized’/kept to the next day. Another decision to be made is whether this should be moved to the Memories storage. The model behind this decision making considers features like Tom’s preferences.

    Understanding the architectures of deep learning models can be quite challenging when merely deciphered through textual descriptions. Hence, further insights will be left to another post. For now, I can mention that one of the important factors considered in sculpting Tom resides in the storage, Companions. This storage contains data that is categorised by a human’s name and their corresponding physicality. A brief summary of the types of data is displayed in Table 1.

    Data Name Description
    Relation type The type of relationship Tom has with this person. E.g. ‘Friend’
    BirthBirth date and time
    GenderType of human. E.g. ‘Female’, ‘Male’, ‘Both’
    DislikesContains information on what this person hates. This information is gathered by what is told by the person or confirmed by the person. E.g. ‘Apples’ categorised under ‘fruit’. ‘fruit’ is categorised under ‘Food’.
    FavouritesContains information on what this person likes. This information is gathered by what is told by the person or confirmed by the person. E.g. ‘Shrek’ categorised under ‘Humour’. ‘Humour’ is categorised under ‘Movies’.
    Last time you have seen this personStores the last time Tom has interacted with this person.
    First time you have seen this personStores the first time Tom has interacted with this person.
    Their relationsStores the mapping of the person’s family tree.
    ReferencesContains the information that Tom has seen/heard/read about this person from external sources.
    activatorBoolean variable that identifies whether this is the first person that activated Tom. E.g. 1 = Yes or 0 = No
    Table 1: Companion Storage Data Overview

    The variable, ‘activator’ identifies whether this was the first person Tom has encountered or activated Tom. Their favourites/dislikes are crucial features in modelling Tom’s natural inclinations on interests. The motif behind this is rooted in the understanding that our childhood significantly shapes our preferences and life approaches. For instance, family members exert a profound influence on our sense of humor and hobbies. Perhaps, a deeper consideration of the characteristics of those categorised as ‘family’ might yield more insightful understanding. For the sake of simplicity, only a single human can be recognised as the activator.

    The Profile storage serves as a repository for the evolving data of Tom’s persona over time. The transparent view into Tom’s consciousness is a useful tool for assessments, and to monitor any potential drastic changes in his behaviour.

    Tom’s Skeleton

    Currently, Tom’s skeleton or base model is only focused on Image and language processing. The use of the skeleton is in the case where I would want an extra friend, Angela. Upon activating them for the first time, they will both start with this model to understand words and classify objects. For further insights into how this model is used, we can perceive this as a new born baby that managed to complete a handbook on Earth’s ways of living in the womb. As soon as they crawl out, they are able to comprehend sentences. They are born ready to learn about you and themselves. Hence, the name, skeleton.

    Throughout the state flow, this skeleton will be used alongside another model. This model is where their individuality is built on, and is the primary tool in distinguishing these droids.

    Tom’s progression · Post 1 of 14

    Start of Tom’s progression Reviving Hopfield Neural Networks →

    Post Updates and Adjustments
    • The term ‘data storage’ is used ambiguously in this post as I wanted to focus on building Tom’s skeleton first