<?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 MONKEYPATCHED on Medium]]></title>
        <description><![CDATA[Stories by MONKEYPATCHED on Medium]]></description>
        <link>https://medium.com/@prashun_33126?source=rss-6d4240051725------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*arUaHm4brSRIedM68363-w.png</url>
            <title>Stories by MONKEYPATCHED on Medium</title>
            <link>https://medium.com/@prashun_33126?source=rss-6d4240051725------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:28:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashun_33126/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[SPATIO TEMPORAL TRANSFORMERS]]></title>
            <link>https://medium.com/@prashun_33126/spatio-temporal-transformers-a573cbc356f2?source=rss-6d4240051725------2</link>
            <guid isPermaLink="false">https://medium.com/p/a573cbc356f2</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[robots]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[spatio-temporal]]></category>
            <dc:creator><![CDATA[MONKEYPATCHED]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 17:16:11 GMT</pubDate>
            <atom:updated>2024-11-29T17:16:11.860Z</atom:updated>
            <content:encoded><![CDATA[<p>After determining the most optimal path using reinforcement learning, we designate specific locations along this path at intervals of every t seconds, recording the trajectory in a time series database. In our framework, these designated locations are referred to as “Keyframes.” To verify that the robot adheres to the prescribed path, we obtain sensor readings from the robot at every t seconds. For instance, when utilizing images from a camera, we perform feature extraction on the captured images and compare the current image features with those from previous images. This comparison allows us to confirm that the robot has successfully reached the Keyframe and to update its current positional information relative to the global map. This process forms the foundation of our visual Localization and Mapping algorithm.</p><p>As the robot moves in the map its environment is always changing therefore it is important for the robot to detect the action or motion of the other robots or humans in the environment. Action and motion prediction for humanoid robots involves forecasting the future states, movements, or actions of either the robot itself or surrounding agents (like humans or other robots) based on observed data. This capability is crucial for tasks such as human-robot collaboration, autonomous decision-making, and adaptive interaction in dynamic environments.</p><h3><strong>Key Concepts in Action and Motion Prediction</strong></h3><ol><li><strong>Action Prediction</strong><br>Involves determining the next high-level task or behavior a humanoid or a human is likely to perform.</li><li><strong>Motion Prediction</strong><br>Focuses on estimating the future trajectory of an agent (robot or human) or object in space.</li><li><strong>Multi-Modal Inputs</strong><br>Motion and action predictions often rely on diverse data sources such as:</li></ol><ul><li><strong>Visual Inputs</strong>: Cameras for detecting gestures, postures, and object locations.</li><li><strong>Kinematic Data</strong>: Joint angles, velocities, and accelerations.</li><li><strong>Sensor Data</strong>: Proximity sensors, force sensors, and environmental maps.</li></ul><p><strong>4. Probabilistic Modeling</strong><br>Prediction often incorporates probabilistic models to account for uncertainty in dynamic environments.</p><h3><strong>Feature prediction using spatio temporal transformers</strong></h3><p>Temporal relations are the main factors for developing a strong understanding of content in a video, thus we require a separate algorithm for videos than In image processing, Videos are essentially a sequence of frames, and processing them requires techniques to capture and incorporate motion information. The VLM transformer ignores the temporal (time) relations between frames and only focuses on a frame’s spatial (space) information and are thus not suitable for video predictions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*51CYgXbSytKBNsqAg_ul-w.png" /></figure><p>Traditionally the most performant models for video prediction are based on deep 3D convolutional architectures which are a natural extension of image classification CNNs. Their output shape is a 3 dimensional volume space such as cube or cuboid that represents a specific area of the video (tubelets) . They are helpful in event detection in videos, 3D medical images etc. however they are not limited to 3d space but can also be applied to 2d space inputs such as images where we consider time to be the third dimention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*mTSzs11XFeXjU0SneNNj6g.png" /></figure><p><strong>Next frame predictions thus </strong>comes under the sequence-to-sequence problems where the input is a sequence of continuous image frames and the expected outcome is also a sequence of image frames or video for some short duration. Most commonly used next frame prediction models include models like ConvLSTM which uses a combination of LSTM and Convolutional Neural Networks to capture the spatio temporal relationships between frames . The model works well but as noted earlier, it consumes a lot of memory and time during training. The memory consumption is due to weights in the ConvLSTMs and the sequential nature of the input also the model does not allow much parallelization to reduce the training time. By this time it is quite evident that if we try to build a ConvLSTM network that uses 3 Dimentional convolutions for predicting the next sequence of frames it will not be very computationally efficient we therefore explore transformer based models to solve this problem mainly due to its ability to do parallel processing</p><p>Transformer-based models are known to be more effective when large training datasets are available especially for sequence to sequence generation task , Inspired by ViT, and the fact that attention-based architectures are an intuitive choice for modelling long range contextual relationships in video many transformer only video models have been proposed .These models calculate self-attention on a sequence of spatio-temporal tokens that are extracted from the input video. we therefore propose a spatio-temporal transformer based model for next frame prediction.</p><p>Our model extracts spatio-temporal tokens from the input video, which are then encoded by a series of transformer layers. The transformer model is composed of two main components: the spatial transformer and the temporal transformer. The spatial transformer is responsible for processing the spatial information of each frame in the video, while the temporal transformer is responsible for processing the temporal information between frames. These two components work together to provide a comprehensive understanding of the video data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*iWTzB35vbzafe1Ya4kDoMg.png" /></figure><h3><strong>Preprocessing the video</strong></h3><p>The first step is to split the video into individual frames. This allows the model to process each frame independently and extract features from each frame. Then for each frame we do the following steps</p><ol><li><strong>Resizing and normalizing the frames: </strong>After the frames are extracted, they are typically resized to a common resolution and normalized to have zero mean and unit variance. This is done to ensure that the model is not biased towards larger or brighter frames.</li><li><strong>Feature extraction </strong>: Features are extracted for each frame using a CNN backbone . For each incoming frame the feature similarity to the previous frame is calculated and similar frames are discarded, this thereby lowers the number of tokens that need to be studied, lowering costs significantly.The feature extraction can be implemented with various convolutional neural network (CNN) backbones as the foundation for feature extraction. for this purpose we use <strong>MobileNetV3 </strong>A widely used and well-performing CNN architecture at the edge and a swin transformer Our model uses CNNs to capture local information and transformers for global context, by combining the strengths of Convolutional Neural Networks (CNNs) and Transformers in a more efficient architecture we reduce the memory usage and computational complexity of the model and increase its accuracy</li></ol><h3><strong>Local feature extraction using MobilenetV3</strong></h3><p><strong>MobileNetV3</strong> is a deep learning model architecture designed primarily for mobile and embedded vision applications. It is an evolution of the earlier MobileNet models, which are lightweight and optimized for speed and efficiency, particularly in constrained environments like mobile devices with limited computing power and memory. MobileNetV3 improves on the performance and efficiency of MobileNetV2 by introducing new techniques such as the use of neural architecture search (NAS) and better activation functions.</p><p>MobileNetV3 introduces several optimizations that make it smaller, faster, and more power-efficient while maintaining strong performance on image classification tasks.<strong>MobileNetV3</strong> is used as the backbone network that extracts local features from the input image. Since MobileNetV3 is designed for classification tasks, you need to modify its final layers (like the fully connected layers used for classification) to suit the object detection task.</p><h3><strong>Global feature extraction using Swin transformer</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*v-8ZKsPqS4iY6aMNB5Z0Qw.png" /></figure><p>As seen from above architecture full self-attention can be computationally expensive, especially when applied to large input images. Sparse attention techniques can be used to reduce the computational complexity by focusing only on local or relevant regions of the image, rather than computing attention across all patches. This is done with the help of a Swin Transformer ,The Swin Transformer employs window-based attention, where attention is computed within local windows, thus reducing the overall computation while retaining relevant spatial information. and providing:</p><ul><li><strong>Efficiency:</strong> By limiting attention calculations to local regions, the Swin Transformer scales more efficiently with image size.</li><li><strong>Performance:</strong> It achieves state-of-the-art performance on several computer vision tasks like image classification, object detection, and semantic segmentation.</li></ul><p>Instead of processing the entire image as one, swin transformer processes images at different scales (similar to a convolutional neural network, CNN). It starts with smaller patches and gradually merges them to form larger representations. This allows the model to capture both fine-grained details and high-level features of the image.</p><p>The major component of the architecture is the Video Swin Transformer block, which is built by replacing the <strong>multi-head self-attention</strong> (MSA) module in the standard Transformer layer with the <strong>3D shifted window-based multi-head self-attention module. </strong>The <strong>inductive biases</strong> of <em>locality, hierarchy and translation invariance</em>, enable the swin transformer to serve as a general-purpose backbone for various image recognition tasks.</p><p>First, the input (an RGB image) is split into non-overlapping patches. the size of each patch, is 4 * 4 * 3 , much smaller than the patches in ViT, which is 16 * 16 * 3. Then, there are four stages in the architecture. Stage 1 consists of a linear embedding layer Next, stages 2, 3, and 4, each consists of a patch merging layer and a Swin Transformer Block.</p><h3><strong>Generating the tubelet embeddings</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*tOGcbVoS835jFSv94ZYBAw.png" /></figure><p>The output of the swin transformer is a feature vector for each of the windows ,which are then spatially encoded to maintain the windows position. If we add the dimension of time to each of the tokenized patches then we get a volume containing the patches and windows of the frame and the temporal information as well. These spatio-temporal volumes are then flattened to build video tokens called as tubelets.</p><p>Essentially, a tubelet is a 3D block of video data, comprising a series of consecutive frames (temporal information) within a specific spatial region (like a small patch of an image). Instead of treating video frames independently, the tubelet representation integrates information across the sequence of frames, providing a more <strong>holistic</strong> understanding of the object’s behavior over time.</p><h3><strong>Adding the temporal positional encoding</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*BiCS33TL9gQHyHXJMb9C4w.png" /></figure><p>To add <strong>temporal encoding</strong> to the Swin Transformer output, you’ll need to embed temporal information from a sequence of images (e.g., frames in a video) and then integrate this temporal encoding into the feature representation.</p><pre> def create_temporal_embedding(self, num_frames):<br>        &quot;&quot;&quot;<br>        Create temporal embedding for each frame.<br>        This can be a learnable embedding or sinusoidal temporal embedding.<br>        &quot;&quot;&quot;<br>        embed_dim = self.swin_transformer.num_features  # The output embedding size of the Swin Transformer<br>        <br>        # Sinusoidal or learnable embedding for temporal dimension<br>        temporal_embedding = nn.Parameter(torch.zeros(1, num_frames, embed_dim))  # Learnable temporal embedding<br>        nn.init.trunc_normal_(temporal_embedding, std=0.02)  # Initialize<br>        <br>        return temporal_embedding</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*yUcrcRFn0YKBOy85rUOYbA.png" /></figure><p>To add <strong>spatio-temporal embedding</strong> to the <strong>Swin Transformer</strong> output, the process typically involves appending or merging the spatial position information with the feature map produced by the Swin Transformer after adding the temporal encodings. adding a spatial embedding ensures that the model takes spatial relationships between patches into account</p><pre> def create_spatial_embedding(self, num_patches):<br>        &quot;&quot;&quot;<br>        Create a 2D spatial embedding for each patch.<br>        This can be done using a simple learnable embedding or a sinusoidal positional embedding.<br>        &quot;&quot;&quot;<br>        embed_dim = self.swin_transformer.num_features  # Dimensionality of the embedding (matches transformer output)<br>        <br>        # Sinusoidal embedding: You can use torch or numpy to generate a fixed positional encoding<br>        spatial_embedding = nn.Parameter(torch.zeros(1, num_patches * num_patches, embed_dim))  # Learnable embedding<br>        nn.init.trunc_normal_(spatial_embedding, std=0.02)  # Initialize<br>        <br>        return spatial_embedding</pre><h3><strong>Processing the spatio temporal embeddings to predict the next action</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Rfz2LxW1guaSaeErTQR1OQ.png" /></figure><p>We use tubelet sampling as our tokenization scheme and then use these tokens to predict the next sequence of frames. As this is a sequence — to — sequence model a GPT network is used to predict the next patch similar to an NLP problem below is the conceptual pseudocode</p><p>For text sequences Encoder-decoder models (also called <em>sequence-to-sequence models</em>) use both parts of the Transformer architecture. At each stage, the attention layers of the encoder can access all the words in the initial sentence, whereas the attention layers of the decoder can only access the words positioned before a given word in the input.</p><p>During encoding the self-attention enables models to weigh the importance of different parts of the input sequence when making predictions or capturing dependencies between the frames thus non important parts of the input sequence are ignored speeding up the prediction mechanism.</p><p>Or model treats video frames as a sequence, similar to how GPT handles text. The model learns to predict future frames or generate new sequences based on past frames. It does this by applying spatio temporal attention to the vectors and then passing the vectors to a encoder block In this paper, we focus on the most common video prediction task, i.e. predicting <em>N</em> future frames given <em>L</em> past frames, with <em>L</em> and <em>N</em> being greater than 1.</p><p>Now that You’ve trained your transformer model, and now, at the prediction phase, the architecture behaves slightly differently than it does during training. During Inference, The main difference occurs in the decoder. The decoder generates tokens step by step, using the previously generated tokens and the encoded input information to inform its decisions. At each step, the model selects the token with the highest probability as the predicted token, and this predicted token is then fed as input to the next step.</p><p>The decoder is a crucial part of the transformer architecture for tasks that involve generating sequences, as it enables the model to learn complex relationships between input and output sequences and generate coherent and contextually appropriate outputs. It’s important to note that while the encoder and decoder are separate parts of the transformer model, they often share parameters and are trained jointly to optimize the end-to-end performance of the model on future frame prediction task.</p><h3>General Workflow for Frame Prediction :</h3><ol><li><strong>Data Preprocessing</strong>:</li></ol><ul><li>Convert video frames into tensors of shape [batch_size, num_frames, channels, height, width] or extract features using a backbone like a CNN, Swin Transformer, or 3D CNN.</li></ul><ol><li><strong>Encoder</strong>:</li></ol><ul><li>The encoder takes the sequence of past frames and encodes each frame into a fixed-dimensional latent representation.</li><li>Use a Transformer encoder (with multi-head self-attention) to extract features from the past frame sequence.</li></ul><ol><li><strong>Decoder</strong>:</li></ol><ul><li>The decoder uses the encoded representations of the past frames and predicts the future frames.</li><li>It generates one future frame at a time, where each prediction step can also take into account the previously predicted frame (autoregressive behavior).</li></ul><h3><strong>Loss Function</strong>:</h3><p>In the context of video, let’s say you have a sequence of 10 frames, and you want to predict the 11th frame. The input to the model is the first 10 frames, and the ground truth for training is the 11th frame. The predicted 11th frame is compared with the actual 11th frame, and the loss measures how far off the prediction is from the true frame.</p><p>Since video involves temporal sequences, it’s important to ground changes in the images to real-world events or progressions. This ensures that the video evolves naturally over time, with grounded transitions between frames.The loss is typically a pixel-wise loss, such as mean squared error (MSE), between the predicted frame and the ground truth future frame. The</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Q5T06uAxdz4vc7Ft5qUvsQ.png" /></figure><p><strong>Temporal Consistency Loss</strong>: term calculates the cosine similarity between consecutive frames.This approach encourages the direction of the feature vectors to be aligned across time., which enforces smoother transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*SeUZ5Nc-DD0tlvTjhfwDQw.png" /></figure><h3><strong>Scene level grounding the predicted frames</strong></h3><p>To safely and rationally participate in dense and heterogeneous traffic, humanoid robots require to sufficiently analyze the motion patterns of surrounding traffic-agents and accurately predict their future trajectories. Therefore for each of the N frames we then add the spatial encoding and pass the embeddings to an encoder .</p><p>The encoder self-attention mechanism is a crucial component responsible for capturing spatial relationships and dependencies within the feature maps extracted from the input image. The feature maps are then flattened into a sequence of feature vectors. Each position in the sequence corresponds to a spatial location within the feature maps. Before applying self-attention, these feature vectors are linearly transformed into query, key, and value vectors using learned weight matrices. This transformation projects the feature vectors into a higher-dimensional space suitable for computing attention scores.</p><p>Each position in the sequence of feature vectors now has associated query, key, and value vectors. These vectors represent the content and spatial information of the corresponding spatial locations within the feature maps. The self-attention mechanism computes attention scores between each pair of feature vectors in the sequence. For each position, the attention scores indicate the relevance or importance of other positions in the sequence .Self-attention dynamically adjusts the importance given to different patches. For example, if a certain patch contains part of an object, self-attention can help focus on other patches that contribute to identifying that object. This means that the model doesn’t need to rely on predefined kernels or pooling layers to determine which regions are important — it <strong>learns</strong> which parts of the image are relevant through attention.</p><p>The extracted features are used to discover the images that portray common parts of the scene. If two points in different images have the similar features, these points can be considered as being the same point in the scene. So we can find overlapped images by searching images that have sufficient number of common points. The simplest way to do this is the exhaustive search, but many approaches are proposed to tackle the problem of scalability and efficiency.</p><p><strong>Scene level Grounding</strong>: The generated frames must be grounded to specific scenes or objects, ensuring the presence, position, and appearance of objects remain consistent throughout the video. This grounding is based on object detection, segmentation, and other features that ensure video coherence. in order to ensure that our generated frames are spatially consistent we calculate a spatial consistency loss between the predicted and actual feature vectors and then back propagate the loss through the encoder <strong>spatial consistency loss</strong> ensures that objects maintain their correct positions across frames, preserving their trajectory and motion without spatial drift. This is essential for generating temporally consistent and smooth videos. By extracting features from our network and comparing them across images, this loss helps preserve high-level spatial structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*um3GzLxBoogcrFieejux-g.png" /></figure><p>The goal is to capture differences between the feature representations learned by the model for specific patches. This is useful when you want to preserve fine-grained details or textures in specific patches. for this we use <strong>Patch NCE (Neighborhood Contrastive Estimation) </strong>the loss is popular for patch-based feature extraction. It contrasts features of patches in the target image with those in the input, aiming to minimize the distance for corresponding patches while maximizing it for non-corresponding patches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*q_fkhxbnTPLdDHoooo7Bxg.png" /></figure><h3><strong>The total loss for predicting the frame</strong></h3><p>Considering above the total loss of or transformer should be above the total loss of or transformer should be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*X52OUf9qrxGRVCrVrUMNiA.png" /></figure><h3>Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*DGk4pW7a-TYEvv6OR2TqcQ.png" /></figure><h3>1. Action Recognition</h3><ul><li><strong>Use Case</strong>: Classifying actions in video sequences.</li><li><strong>Reason</strong>: The model benefits from understanding both the spatial configuration of objects and their motion over time.</li></ul><h3>2. Motion Estimation</h3><ul><li><strong>Use Case</strong>: Analyzing the motion of objects in videos.</li><li><strong>Reason</strong>: Temporal loss helps ensure that motion representations are consistent across frames, while spatial loss ensures accurate representation of the objects.</li></ul><h3>3. Multi-View Video Analysis</h3><ul><li><strong>Use Case</strong>: Analyzing videos captured from multiple viewpoints.</li><li><strong>Reason</strong>: Spatio-temporal loss can help synchronize and align features across different camera angles.</li></ul><h3>Future Directions</h3><ol><li><strong>Multi-Agent Coordination</strong><br>Simultaneous prediction for multiple robots and humans interacting in shared spaces.</li><li><strong>Self-Supervised Learning</strong><br>Leveraging robot’s own experiences to refine motion and action predictions without labeled data.</li><li><strong>Few-Shot Learning</strong><br>Adapting to novel tasks or environments with minimal data.</li><li><strong>Ethics and Safety</strong><br>Ensuring predictions are bias-free, safe, and respect user privacy.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a573cbc356f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DYNAMIC PATH PLANNING]]></title>
            <link>https://medium.com/@prashun_33126/dynamic-path-planning-60a22b28ea48?source=rss-6d4240051725------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a22b28ea48</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[embodied-ai]]></category>
            <category><![CDATA[path-planning-in-robotics]]></category>
            <dc:creator><![CDATA[MONKEYPATCHED]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 16:39:27 GMT</pubDate>
            <atom:updated>2024-11-29T16:43:41.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Path planning using Reinforcement Learning can be an effective way to teach agents how to navigate through complex environments. By defining a clear state space, action space, reward structure, and choosing the right RL algorithm, the system can learn to plan optimal paths. This approach has wide-ranging applications in robotics, autonomous vehicles, and beyond, with many opportunities for improvement through simulation and real-world deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*lD-V_cKZJoSBoA_q.png" /></figure><p>The robot receives a high-level command in natural language (e.g., “Bring me the coffee from the kitchen”). an LLM agent running on the robot will parse the input and then get the corresponding starting and ending location and invoke the global planner a list of keyframes along the path will be returned back to the <strong>global path planning agent </strong>given that we need to find the best path from a given starting point to the goal this adds an extra constraint on the trajectories and those trajectories that would not lead us to the goal can be safely ignored thus giving us a map of all possible trajectories from the starting point to the goal Given that there might be multiple possible trajectories from the current point to the goal it is important to further restrict the trajectories based on some selection criteria like known state of the environment and the actions that can be taken by the robot in the environment .</p><h3><strong>The trajectory planning problem in Robotics</strong></h3><p>We need to find a motion law along a given geometric path, taking into account some predefined requirements.So as to be able to generate suitable reference inputs for the control system of the manipulator.</p><p>The inputs of the trajectory planning are:</p><ul><li>the starting and ending points</li><li>the kinematic and dynamic constraints</li><li>the environment in which the robot operates</li></ul><p>while the output is the trajectory of the most optimal path for the robot to get from the starting to the ending point given the environmental and kinematic constraints , expressed as a time sequence of position, velocity and acceleration values. Most of the proposed trajectory planning algorithms are based on policy based reinforcement learning where the desired output state can be predicted by the help of minimization of loss using an objective function or Q-function,</p><p>The Q-function (a.k.a the state-action value function) of a policy measures the expected return or discounted sum of rewards obtained from the state by taking action first and then calculating the reward there after .</p><p>For most problems, it is impractical to represent the Q-function as a table containing values for each combination of state and action. Instead, we train a function approximator, such as a neural network to estimate the Q-values, This allows the algorithm to handle environments with a large number of states and actions.</p><p>As our agent traverses the environment, it receives positive or negative reward signals for the actions it chooses and the states that it visits. Our goal is to learn a policy from these reward signals that maximizes total reward across an entire trajectory sampled from the policy. This idea is captured by the return, which sums the total rewards over an agent’s trajectory; see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*PzSfXPi6NwiHXGBs.png" /></figure><p>we learn this policy using gradient ascent to maximize the total sum of the reward . Gradient ascent/descent is a fundamental optimization algorithm that — <em>along with its many variants</em> — is heavily used for training machine learning models across a variety of different applications. If we select the correct learning rate and perform sufficient iterations of this gradient ascent update, our policy should begin to increase the desired objective — <em>this is the fundamental idea behind policy optimization</em>. As long as we instantiate our policy such that the gradient of action probabilities is computable we can then predict the next action-state pair and thus the trajectory. In other words, we can train a network to predict the trajectory given a starting and ending point, for this we calculate the several possible trajectories by letting the agent interact with the environment and then saving them in an experience replay buffer and then applying gradient ascent algorithm to the results , selecting the path with the maximum rewards.</p><p>An obvious problem in training the robot in the above method is the large amount of variability in the environments in which the robot may have to operate.,also getting good results via policy gradient methods is challenging because they are sensitive to the choice of step size — too small, and progress is hopelessly slow; too large and the signal is overwhelmed by the noise, or one might see catastrophic drops in performance.since we want to use our model for localization it s important that the step size is kept in synchronization with the number of tiles as each tile represents one step .</p><h3>A3C</h3><p>One disadvantage of policy based learning method is that they also often have very poor sample efficiency, taking millions (or billions) of timesteps to learn simple tasks. This significantly increases the overall training time required by the robot to explore different environments to solve for this we propose the use of the A3C network</p><p>The Asynchronous Advantage Actor-Critic (A3C) is a powerful reinforcement learning algorithm that enables agents to learn optimal actions in complex environments.A3C introduces the idea of asynchronous training to address the inefficiency of traditional synchronous methods. Multiple copies of the environment run in parallel, and each copy has its instance of the actor-critic network. These parallel agents explore the environment independently and update the globally shared parameters asynchronously<a href="http://asynchronously.it/">. </a>The model also allows us to train our machine learning models using data that is distributed across multiple devices without centralizing the data in a single location thus improving the overall collective experience</p><p>A3C (Asynchronous Advantage Actor-Critic) with LSTM (Long Short-Term Memory) is an extension of the standard A3C algorithm, designed to handle tasks with temporal dependencies, such as reinforcement learning environments where the agent needs to remember previous observations to make decisions (like in partially observable environments).</p><p>A3C has been used to train robots to perform complex tasks, such as grasping objects and navigating through environments. This has significant implications for the field of robotics, as it allows robots to learn from varied experience and adapt to new situations. The three A of the A3c Algorithm give a short summary of the algorithm properties</p><ul><li><strong>Asynchronous</strong>: The algorithm is an asynchronous algorithm where multiple worker agents are trained in parallel, each with their environment. This allows our algorithm to train faster as more workers are training in parallel and attain a more diverse training experience as each worker’s experience is independent. but they share the experience among themselves thus the overall global experience of each agent increases There’s also the added benefit that if one agent gets stuck performing a task sub optimally to get a reward over and over thinking that this is the best way, the other agents can share information and show this agent that there is a better way to solve the problem! the asynchronous updates to update the neural network parameters. also helps in reducing the correlation between the training samples, leading to more stable and faster learning.</li><li><strong>Actor-Critic</strong>: The Actor-Critic aspect of the algorithm uses an architecture that shares layers between the policy and value function</li><li><strong>The Critic</strong> updates the value function parameters w and depending on the algorithm</li><li><strong>The Actor</strong> updates the policy parameters in the direction suggested by the critic.</li></ul><p>A good analogy of the actor-critic is a young boy with his mother. The child (actor) constantly tries new things and exploring the environment around him. He eats its own toys, he touches the hot oven, he bangs his head in the wall (I mean why not). His mother (the critic) watches him and either criticize or compliment him. The child listen to what his mother told him and adjust his behavior. As the kid grows, he learns what actions are bad or good and he essentially learns to play the game called life. That’s exactly the same way actor-critic works.</p><p>The training of the two networks is performed separately and it uses gradient ascent (to find the global maximum and not the minimum) to update both their weights. As time passes, the actor is learning to produce better and better actions (he is starting to learn the policy) and the critic is getting better and better at evaluating those actions. It is important to notice that the update of the weights happens at each step (TD Learning) and not at the end of the episode, as opposed to policy gradients.</p><p>A3C implements a policy gradient network using a feed forward neural network (FFNN) and convolution neural network (CNN). Instead of waiting for the end of the episode like in policy gradients to update our parametrized policy, we are updating it at each step of our episode :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/0*0ZYWRFT9hN_-ajux.png" /></figure><p>It also replace the reward function with a parameter that describes the quality of the action i.e we now calculate the quality of the action at the end of each step so that there is no fixed reward or punishment for each action but rather the quality of the action taken is calculated using a CNN . As the episodes go, our critic is expected to perform better at estimating how good our policy is supposed to be, and as a consequence, our actor will get better and better at choosing the right policy (or at least, that’s what we hope). This quality of descision is updated at each step and is then used to build an approximation function called the value function. It makes a lot of sense to learn the value function in addition to the policy, since knowing the value function can assist the policy update, such as by reducing gradient variance in vanilla policy gradients</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*lcFluS29XlMdRcYw.png" /></figure><ul><li><strong>Advantage</strong>: Advantage is a metric to judge how good an action that was determined using the policy gradenent was and how it turned out. This allows the algorithm to focus on where the network’s predictions were lacking and try to update the policy accordingly .</li></ul><p>The advantage metric is given by the following expression:- <strong>Advantage: A = Q(s, a) — V(s) </strong>The Q(s, a) refers to the Q value or the expected future reward of taking an action at a certain state. The V(s) refers to the value of being in a certain state. The objective of the model is to maximize the advantage value</p><p>By using the value of advantage , the agent also learns how much better the rewards were than it’s expectations. This gives a new-found insight to the agent into the environment and thus the learning process is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*YVrnwwLINRVzOqtj.png" /></figure><ul><li><strong>The Global learner:</strong> Federated learning (often referred to as collaborative learning) is a decentralized approach to training machine learning models. Here’s a general overview of how federated learning could be applied to the critic component in actor-critic networks:</li></ul><ol><li>Agents or devices (such as edge devices or servers) hold their own local datasets.</li><li>The critic network is present on each of these devices.</li></ol><p>the global critic network serves as the starting point for each local critic. Each device independently trains its local critic using its local dataset and the global critic as a starting point. The local training process involves computing gradients based on local experiences and updating the local critic parameters. After local training, the updated critic models from each device are aggregated to form a global critic model. This can be done using techniques like Federated Averaging, where the parameters are averaged across devices with appropriate weighting. The global critic is then updated with the aggregated model.</p><p>First, the worker agent resets the global network, and then they start interacting with the environment. Each worker follows a different exploration policy to learn an optimal policy. Following this, they compute value and policy loss and then they calculate the gradient of the loss and update the gradients to the global network. The cycle continues as the worker agent starts resetting the global network and repeats the same process. images and sensor data from each of the simulations are used to generate trajectory data their trajectory data is then aggregated in a global network.</p><h3><strong>Steps:</strong></h3><ul><li>Build our actor-critic network</li><li>Build our worker agents</li><li>Defining the training function for the worker</li><li>Build our master agent supervisor</li><li>Implement the A3C algorithm</li><li>Train our agents</li><li>Visualize our performance</li></ul><h3>Action space</h3><p>1 — start</p><p>2 — stop</p><p>3 — left</p><p>4 — right</p><h3>Observation space</h3><p><strong>State</strong>:</p><ul><li>agent moved to new cell</li><li>agent runs into a obstacle</li><li>agent reached the goal</li></ul><h3>Starting condition</h3><ul><li>location (x,y coordinate)</li></ul><h3>Ending conditions</h3><ul><li>location (x,y coordinate) reached</li><li>max number of tries (100) made</li><li>reward falls below 0,1</li></ul><h3>Goals</h3><p>The agent aims to collect the maximal total reward during a simulation while moving from the starting point and stopping and the given ending point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*h6Dd4ZzezeSNpc2x.png" /></figure><h3>Reward Structure</h3><ul><li>Our rewards will be floating points ranging from -1.0 to 1.0.</li><li>Each move from one state to the next state will be rewarded as 1.0</li><li>The robot is said to have changed the state <strong>when x,y co ordinate changes</strong></li><li>An attempt to enter a blocked cell (“red” cell or obstacle like a shelf) will cost the robot -0.75 points! This is a severe penalty, so hopefully the robot will learn to avoid it completely. Note that an attempt to move to a blocked cell is invalid and will not be executed. But it will incur a -0.75 penalty if attempted.</li><li>The same rule holds for an attempt to move outside the maze boundaries: -0.75 points penalty.</li><li>The robot will be penalized by -0.25 points for any move to a cell that he has already visited. This is a counterproductive action that should not be taken at all.</li><li>To avoid infinite loops and senseless wandering, the simulation is ended once the total reward of the robot is below the negative threshold of -1 We assume that under this threshold, the robot has “lost its way” and already made too many errors from which he has learned enough, and should proceed to a new fresh simulation.</li></ul><h3>Natural Language integration using LLM Agents and function calling</h3><p>We integrate LLM agents into our workflow to make the path planning process more general purpose. LLM agents refer to applications or systems that leverage Large Language Models (LLMs) to perform specific tasks autonomously or semi-autonomously. These agents are designed to understand, process, and generate human-like language while solving problems or performing actions across various domains.</p><p>By leveraging the language generation capabilities of an LLM to trigger the navigation actions and then combining them with reinforcement learning we can use LLMs to create agents that can plan, execute, and refine their actions toward our navigation goals.</p><p>We deploy Ollama to support our agents . Ollama provides a straightforward interface for running and interacting with LLMs on your own hardware. It supports fine-tuning, deployment, and usage of various open-source LLMs (e.g., LLaMA, Mistral, or Falcon). Its focus is on privacy, allowing users to avoid sending data to external servers. Ollama can be used as a backend for LLM agents through APIs or by integrating it with frameworks like LangChain or a custom Python script. We use Mistral 7B as our base LLM and Langchain as our framework .</p><h3>5. End to End pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8vzFF4nlNxSNaAg8.png" /></figure><h3>Core Concepts of Global Path Planning</h3><ol><li><strong>LLM for High-Level Reasoning</strong>:</li></ol><ul><li><strong>Environment Understanding</strong>: LLMs process and interpret environment descriptions, constraints, and goals.</li><li><strong>Semantic Mapping</strong>: Generate abstract plans based on contextual information (e.g., obstacles, priority zones, and targets).</li><li><strong>Decomposition</strong>: Break global path objectives into hierarchical sub-goals for efficient execution.</li></ul><p><strong>2. RL for Optimal Pathfinding</strong>:</p><ul><li><strong>State Exploration</strong>: Explore the state space for feasible routes considering dynamic constraints (e.g., moving obstacles).</li><li><strong>Policy Optimization</strong>: Learn optimal navigation policies by trial-and-error, maximizing rewards for criteria like speed, safety, or energy efficiency.</li><li><strong>Adaptive Behaviors</strong>: Adjust policies based on changes in the environment, such as unexpected blockages.</li></ul><p><strong>3. Integration of LLM and RL</strong>:</p><ul><li>Use LLMs for macro-level reasoning (e.g., strategic path suggestions or replanning).</li><li>Leverage RL for micro-level navigation (e.g., precise control over movements and obstacle avoidance).</li></ul><h3>Algorithm</h3><p><strong>Global optimal path planning</strong></p><ul><li>Read the LLM input to extract the starting and ending point of the path</li><li>Get the map csv from the s3 bucket and load the map into memory</li><li>Use the extracted places from the llm and look up their default locations</li><li>Place the starting and ending points on the map</li><li>Apply reinforcement learning to find the path</li><li>Save the path in the db</li><li>For each keyframe , find if keyframe is within required distance of the path</li><li>if yes add the keyframe to the output path</li></ul><h3>Future Directions</h3><ul><li><strong>Map merging</strong>: merging localized map into a global map</li><li><strong>Adaptive Learning Systems:</strong> Robots that learn and adapt to environments in real-time.</li><li><strong>Energy Optimization:</strong> Enhanced algorithms for longer operational times.</li><li><strong>Multimodal Locomotion:</strong> Switching between walking, climbing, or crawling as required.</li></ul><p>At <strong>Monkeypatched</strong>, we specialize in integrating <strong>Large Language Models (LLMs)</strong> into the world of <strong>robotics</strong>, revolutionizing how robots perceive, interpret, and interact with the world. With cutting-edge innovation and a commitment to excellence, we enable seamless human-robot collaboration and smarter automation. with a vision of building <strong>general-purpose humanoids</strong> designed for a wide range of <strong>industrial tasks</strong>. Our solutions bring intelligence, adaptability, and efficiency to industries, enabling smarter automation and seamless human-robot collaboration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a22b28ea48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GENERATING AN OCCUPANCY MAP]]></title>
            <link>https://medium.com/@prashun_33126/generating-an-occupancy-map-27b93417234e?source=rss-6d4240051725------2</link>
            <guid isPermaLink="false">https://medium.com/p/27b93417234e</guid>
            <category><![CDATA[indoor-mapping]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[mapping]]></category>
            <dc:creator><![CDATA[MONKEYPATCHED]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 16:27:41 GMT</pubDate>
            <atom:updated>2024-11-29T16:45:26.891Z</atom:updated>
            <content:encoded><![CDATA[<p>Path planning is fundamental to autonomous mobile robots, as it enables them to navigate their environment safely, efficiently, and without human intervention. It involves creating a route from a starting position to a destination, taking into account obstacles, dynamic changes in the environment, and optimization of factors like distance, time, and energy usage.</p><p>Path planning continues to evolve with advancements in AI and machine learning, allowing for more adaptive, intelligent, and efficient navigation strategies that improve the safety, reliability, and autonomy of mobile robots. For humanoid robots, path planning becomes more complex due to their human-like structure, multiple degrees of freedom, and specific mobility challenges, such as bipedal locomotion. Unlike wheeled robots, which rely on ground contact stability, humanoid robots must balance themselves dynamically, making their path planning highly intricate.</p><p>We present our work to try and implement a SLAM algorithm on a humanoid robot platform,We first start by testing a visual SLAM algorithm which uses keypoints as visual landmarks and tries to estimate their positions, and adapt it to the specific constraints of the platform. Humanoid robots are very speciﬁc: due to their additional complexity, they cannot carry as many sensors as the others, and have speciﬁc problems due to their way of moving so the challenge here is to enable navigation with as less number of sensors as possible</p><p>Like other autonomous robots, humanoids use sensors for mapping and localization. <strong>Simultaneous Localization and Mapping (SLAM)</strong> helps the robot understand its environment and position within it, a vital input for precise path planning. Sensor fusion from cameras, LIDAR, and IMUs provides the real-time data needed for adaptive movement.</p><p>Visual Simultaneous Localization and Mapping (SLAM) is a cutting-edge technology that combines computer vision , artificial intelligence, and robotics to enable machines to perceive and navigate unknown environments. It allows robots or autonomous systems to understand their surroundings, build a map of the environment, and simultaneously determine their own position within that map.</p><p>Solving the SLAM problem consists of estimating the robot trajectory and the map of the environment as the robot moves in it. Due to the inherent noise in the sensor measurements, a SLAM problem is usually described by means of probabilistic tools.</p><p>The robot is assumed to move in an unknown environment, along a trajectory described by the sequence of random variables x1:T = {x1, . . . , xT }. While moving, it acquires a sequence of odometry measurements u1:T = {u1, . . . , uT } and perceptions of the environment z1:T = {z1, . . . , zT }. the problem can thus be formulated as given the odometry and perception information for a robot at time t in an unknown point in a 2d environment represented as x,y we need to predict the pose of the robot (x,y,z,r,p,y) so that the robot can follow a particular path i.e a robot’s pose consists of its location in and its orientation, which can be represented via Euler angles, quaternions, or rotation matrices.</p><p>Traditional SLAM methods typically rely on range sensors like Lidar or sonar, which provide accurate distance measurements but lack detailed visual information. Visual SLAM, on the other hand, utilizes cameras as the primary sensor, allowing for richer and more detailed perception of the environment. Visual SLAM algorithms extract visual features from camera images, track these features over time, and use them to estimate the camera’s motion and generate a map of the environment.</p><p>The method demonstrated in this example is inspired by ORB-SLAM3 which is a feature-based visual-inertial SLAM algorithm and consists of the following steps</p><h3>Key Components of Path Planning</h3><ul><li><strong>Environment Representation:</strong></li><li><strong>Grid Maps:</strong> Divides the environment into a grid for easier navigation.</li><li><strong>Voronoi Diagrams:</strong> Finds the safest path by maximizing distance from obstacles.</li><li><strong>Probabilistic Roadmaps (PRM):</strong> Generates a graph of feasible paths in a high-dimensional space.</li><li><strong>Octomap:</strong> 3D volumetric maps suitable for humanoids in complex terrains.</li></ul><h3>Grid maps</h3><p>Grid maps are a widely used technique for environment representation in robotic path planning. They discretize the environment into a grid structure, where each cell represents a specific region in the space and contains information about its traversability (e.g., free space, obstacle, unknown). Our first object therefore is for the robot to sense its environment and create a grid map so that it can make informed navigation decisions .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*pjHcyQwWEXO7DydtNVMVZA.png" /></figure><p>In order for us to facilitate navigation of the robot a detailed digital maps of the building’s layout are created. These maps include walls, doors, furniture, etc., which act as references for location determination.T he localization process is further facilitated by dividing the map into smaller, discrete sections or grid-like areas (tiles) . These tiles help create a structured framework for identifying precise locations within an indoor environment.</p><ul><li>These tiles can vary in size depending on the desired accuracy. For example, in a large building, each tile might represent a 1m x 1m section of floor space.</li><li>Each tile is assigned specific coordinates or a unique identifier, making it easier to reference or pinpoint locations within that grid.</li></ul><p>The main idea of tile-based localization is to treat the robot’s position as falling within one of the predefined tiles on the map. When the localization system computes the user’s position, it estimates the tile in which the user is located based on the data collected from the environment (Wi-Fi signals, Bluetooth beacons, etc.). Our system uses dead reckoning (movement estimation), it tracks the robots ’s steps and matches their movement across tiles, updating the robot’s position based on the number of tiles crossed. The use of tile based mapping and localization provides the following advantages</p><ul><li><strong>Simplicity:</strong> Dividing the space into tiles simplifies the localization problem by breaking down the environment into smaller, manageable sections.</li><li><strong>Enhanced Accuracy:</strong> When combined with fingerprinting or probabilistic models, tile-based localization improves positioning accuracy by narrowing down the user’s location to a specific grid section rather than a broad estimate.</li><li><strong>Flexible Resolution:</strong> The tile size can be adjusted based on the desired level of granularity. A smaller tile size offers higher localization accuracy but requires more detailed mapping and computation.</li><li><strong>Easier Integration:</strong> Tile-based systems are easier to implement in certain applications like warehouses, malls, or museums where spaces can be clearly divided into distinct areas.</li></ul><h3>Preprocessing data to create grid maps</h3><p>The first step in a visual SLAM pipeline involves extracting distinctive visual features, such as corners, edges, or blobs, from the camera images. These features serve as landmarks that can be tracked over time.The 3-D points and relative camera pose are computed using triangulation</p><p>Triangulation is a geometric process used in visual SLAM to estimate the 3D position of a feature point in the world based on its projections in two or more camera views. The underlying principle behind triangulation is to find the intersection of rays originating from the camera centers and passing through the image points. By computing the 3D position of these map points, the visual SLAM system can create a sparse 3D map of the environment.</p><p>Calculating the camera projection matrix is an essential step in computer vision, especially for tasks like 3D reconstruction and camera calibration. The camera projection matrix combines intrinsic and extrinsic parameters of the camera.</p><p><strong>Intrinsic Parameters</strong>: These define the camera’s internal characteristics:</p><ul><li>Focal length (fx, fy)</li><li>Optical center (cx, cy)</li><li>Skew coefficient (typically 0 for most cameras)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*pGaCbbHkjRpCMyFz.png" /></figure><p><strong>Extrinsic Parameters</strong>: These define the camera’s position and orientation in 3D space, represented by a rotation matrix R and a translation vector t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*aXraOyyIusjX4zDV.png" /></figure><p>The intrinsic and extrinsic matrices are combined to produce the projection matrix P This projection matrix can then be used for projecting 3D points onto the 2D image plane and vice versa thus we can generate a 3d point cloud using only a camera If a plausible transformation can be estimated between the images, they are considered geometrically verified.The transformation matrix of the camera can then be used to project 3d points to a 2D space and 3D points to a 2D space. example code for calculating the camera matrix is given below</p><pre>def calculate_projection_matrix(fx, fy, cx, cy, R, t):<br>    &quot;&quot;&quot;<br>    Calculate the camera projection matrix.    :param fx: Focal length in x<br>    :param fy: Focal length in y<br>    :param cx: Optical center x<br>    :param cy: Optical center y<br>    :param R: Rotation matrix (3x3)<br>    :param t: Translation vector (3x1)<br>    :return: Projection matrix (3x4)<br>    &quot;&quot;&quot;<br>    # Intrinsic matrix<br>    K = np.array([[fx, 0, cx],<br>                  [0, fy, cy],<br>                  [0, 0, 1]])    # Create the extrinsic matrix [R|t]<br>    extrinsic_matrix = np.hstack((R, t.reshape(-1, 1)))    # Camera projection matrix<br>    P = K @ extrinsic_matrix<br>    return P# Example values<br>fx = 800  # Focal length in x<br>fy = 800  # Focal length in y<br>cx = 320  # Optical center x<br>cy = 240  # Optical center y# Example rotation matrix (3x3) and translation vector (3x1)<br>R = np.eye(3)  # Identity matrix for no rotation<br>t = np.array([0, 0, 5])  # Translate along z-axis# Calculate the projection matrix<br>P = calculate_projection_matrix(fx, fy, cx, cy, R, t)print(&quot;Camera Projection Matrix:\n&quot;, P)</pre><p><strong>feature matching and PRM graph creation using LLMs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*nxnC2U5WTrRern5d.png" /></figure><p>As the camera moves through the scene, it captures multiple frames. By comparing these frames, we can determine the relative motion and extract depth information. if the difference is large enough we mark the frame as a key frame . key frames are a subset of video frames that contain cues for localization and tracking. Two consecutive key frames usually indicate a large visual change caused by a camera movement.</p><p>Instead of using feature detectors,we use transformers for feature matching or local feature matching with transformers LoFTR . LoFTR uses a learning-based approach to feature matching and is invariant to certain transformations, meaning it can handle variations in lighting, angle, or perspective. This is crucial when dealing with images that might be photographed under different conditions.</p><p>The output of this stage is a graph with key frame images as nodes and verified pairs of keyframe images as edges. Two key frames are connected by an edge if they share common map points. The weight of an edge is the number of shared map points.As the robot moves around, more and more nodes are added to the graph and over time, the graph constructed by the mobile robot becomes very large in size, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*aWurBYXTwMc8x26q.png" /></figure><p>so for the purpose of efficiency the scene graph is built offline . once the key frames are known the required pose of the robot can be recorded at each key frame thus multiple trajectories that can be taken by the robot from a position P with orientation θ are recorded .</p><p><strong>IMU alignment and sensor fusion</strong></p><p>once features are extracted, they are tracked across consecutive frames to estimate their motion and enable the estimation of the camera’s ego-motion through the use of epi polar geometry .i.e feature matching is applied temporally to track the object motion in 2D.</p><p>since multiple trajectories hay have the same common key frame between them these trajectories can be joined on key frames to form the graph .we can also track features in 3D across different key frames using the projection matrix to get the 3d points and thus the octo map . Then we find corresponding IMU measurements to align the camera and IMU frames and to find the scale conversion between the IMU and camera odometries. the end of this stage represents a graph of all the possible trajectories that can be taken by the robot in the 3d space .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*dvIb-Ecei2RX6nLVT4i0Wg.png" /></figure><p>Generating an occupancy grid from 3D point clouds involves converting the spatial information from the point cloud into a grid representation, where each cell indicates whether it is occupied, free, or unknown in order for us to get the occupancy grid we need to project the point cloud into the map space once in map space we project each 3d point in the point cloud to a 2d point using the map projection matrix thus giving us a map of all the pixels that are occupied on the grid</p><pre>def create_occupancy_grid(points, grid_size, resolution):<br>    &quot;&quot;&quot;<br>    Create an occupancy grid from a 3D point cloud.    :param points: Nx3 numpy array of 3D points (x, y, z)<br>    :param grid_size: Tuple (width, height, depth) of the grid<br>    :param resolution: Size of each grid cell<br>    :return: 3D occupancy grid<br>    &quot;&quot;&quot;<br>    # Initialize the occupancy grid<br>    occupancy_grid = np.zeros(grid_size, dtype=np.int8)  # 0: free, 1: occupied    for point in points:<br>        # Convert point coordinates to grid indices<br>        x_idx = int(point[0] // resolution)<br>        y_idx = int(point[1] // resolution)<br>        z_idx = int(point[2] // resolution)        # Check if indices are within the grid bounds<br>        if 0 &lt;= x_idx &lt; grid_size[0] and 0 &lt;= y_idx &lt; grid_size[1] and 0 &lt;= z_idx &lt; grid_size[2]:<br>            occupancy_grid[x_idx, y_idx, z_idx] = 1  # Mark the cell as occupied    return occupancy_grid# Example usage<br># Generate a synthetic point cloud (e.g., a simple cube)<br>num_points = 1000<br>points = np.random.rand(num_points, 3) * 10  # Random points in a 10x10x10 space# Define grid size and resolution<br>grid_size = (10, 10, 10)  # 10 cells in each dimension<br>resolution = 1.0  # Each cell represents a 1x1x1 unit# Create the occupancy grid<br>occupancy_grid = create_occupancy_grid(points, grid_size, resolution)# Print the occupancy grid<br>print(&quot;Occupancy Grid:\n&quot;, occupancy_grid)</pre><h3><strong>Algorithm</strong></h3><ul><li>Read the RGBD abd IMU data from the camera using the RealSense SDK 2.0 and Python Wrapper</li><li>Write the frames to S3 bucket in AWS</li><li>Write the IMU data to Kinesis and save in s3 with time stamp</li><li>Validate the input data and save the validated data in S3 bucket</li><li>For each input frame get the previous frame and do a feature comparison using LoFTR</li><li>If the difference is above a threshold mask as keyframe and store in keyframe graph</li><li>Also save the keyframee in postgres to update the location</li><li>For each keyframe extract the point cloud from the image using ORB SLAM</li><li>Project the point cloud to a 2 dimensional space using the camera matrix</li><li>Scale the 2 dimensional map to the the actual area</li><li>Convert the 2 dimensional point cloud to occupance grid by joining the points</li></ul><p>At <strong>Monkeypatched</strong>, we specialize in integrating <strong>Large Language Models (LLMs)</strong> into the world of <strong>robotics</strong>, revolutionizing how robots perceive, interpret, and interact with the world. With cutting-edge innovation and a commitment to excellence, we enable seamless human-robot collaboration and smarter automation. with a vision of building <strong>general-purpose humanoids</strong> designed for a wide range of <strong>industrial tasks</strong>. Our solutions bring intelligence, adaptability, and efficiency to industries, enabling smarter automation and seamless human-robot collaboration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27b93417234e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LANGUAGE MODELS FOR AUTONOMOUS VEHICLES AND ROBOTICS]]></title>
            <link>https://medium.com/@prashun_33126/language-models-for-autonomous-vehicles-and-robotics-9eab9d3a74ae?source=rss-6d4240051725------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eab9d3a74ae</guid>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[llm-app-development]]></category>
            <category><![CDATA[llmrobotics]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[MONKEYPATCHED]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 14:29:22 GMT</pubDate>
            <atom:updated>2024-11-29T16:45:52.655Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to make the robots perform efficiently, robot software is essential to operate the robots according to the needs of the user. This software is an extension of human capability. It reflects the human vision that gets keener with every generation and every technological leap. With the enormous growth of robotics in the industrial sector, the need for robotic software is also increasing substantially.</p><p>A significant aspect of today’s emerging mode of computing is the constantly changing execution environment. The processors available for a task, the devices accessible for user input and display, the network capacity, connectivity, and costs may all change over time and place. In short, the hardware configuration is continually changing. Similarly, the computer user or robot may move from one location to another, joining and leaving groups of people, and frequently interacting with computers while in changing social situations. The seamless integration of various mobile devices, humans, and robots into a unified but ever-changing environment requires a mechanism to allow mobile devices and machines, and robots to act on behalf of their users by registering their capabilities and negotiating the execution of ambience intelligence tasks with each other. We call this collection of mobile and stationary computing devices that communicate and cooperate on the user’s behalf a mobile distributed expert computing system. These systems aim to provide ubiquitous access to information, communication, and computation currently these context-aware works are focused on specific scenarios and cannot be generalized to other applications in order to do so we take the help of integrated expert systems that are context aware</p><h3><strong>Context-aware computing</strong></h3><p>Is a style of computing in which situational and environmental information about people, places, and things is used to anticipate immediate needs and proactively offer enriched situation-aware, and usable content, functions, and experiences. Our focus is on an extended form of mobile computing in which users employ many different mobile, stationary, and embedded computers over the course of the day. In this model, computation does not occur at a single location in a single context, as in desktop computing, but rather spans a multitude of situations and locations covering the office, meeting room, home, airport, hotel, classroom, market, bus, etc. Users might access their computing resources from wireless portable machines and also through stationary devices and computers connected to local area networks. We call this collection of mobile and stationary computing devices that communicate and cooperate on the user’s behalf a mobile distributed computing system. This form of computing is broader than mobile computing because it concerns mobile people not just mobile computers. These systems aim to provide ubiquitous access to information, communication, and computation via the use of ubiquitous technologies like Bluetooth and wifi.</p><h3>Expert systems</h3><p>Expert systems are computer programs designed to mimic the decision-making ability of a human expert in a specific domain. They are a type of artificial intelligence (AI) that uses a knowledge base of human expertise and an inference engine to draw conclusions or make decisions in a particular problem domain. Expert systems are part of the broader field of knowledge-based systems.</p><p>Key components of expert systems include:</p><ol><li><strong>Knowledge Base:</strong> This is a repository of information and expertise in a specific domain. The knowledge base contains facts, rules, heuristics, and relationships that an expert would use to solve problems or make decisions.</li><li><strong>Inference Engine:</strong> The inference engine is responsible for reasoning and drawing conclusions from the knowledge base. It uses various techniques such as rule-based reasoning, case-based reasoning, or logic-based reasoning to process information and arrive at solutions.</li><li><strong>User Interface:</strong> Expert systems often have a user interface that allows users to interact with the system, input data, and receive recommendations or solutions. The interface may be text-based or graphical, depending on the application.</li></ol><p>Expert systems are used in various fields and industries, including medicine, finance, engineering, and troubleshooting complex systems. They excel in situations where there is a well-defined set of rules or a clear knowledge base that can be used to solve problems. Expert systems can provide consistent and rapid decision-making, capturing and preserving the expertise of human professionals.</p><p>Despite their advantages, expert systems also have limitations. They may struggle with uncertainty, lack the ability to learn from experience, and are often confined to the specific domain for which they were designed. Advances in AI, including machine learning, have led to the development of more flexible and adaptive systems, but expert systems remain valuable in certain applications.</p><h3>General purpose robotics — beyond expert systems</h3><p>General-purpose robotics refers to the development of robots capable of performing a wide variety of tasks across different domains, rather than being specialized for a single function. These robots are designed to adapt to new challenges, environments, and requirements by leveraging flexible hardware, advanced software, and often, artificial intelligence (AI). The goal is to create versatile robotic systems that can operate in industrial, domestic, service, and exploratory settings.</p><h3>Key Features of General-Purpose Robotics</h3><h4>1. Adaptability</h4><ul><li>Robots must be able to handle diverse tasks without requiring significant reprogramming or reconfiguration.</li><li>AI and machine learning models enable robots to generalize knowledge from one task to others.</li></ul><h4>2. Autonomy and Decision-Making</h4><ul><li>General-purpose robots often operate autonomously, making decisions based on situational data and pre-trained knowledge.</li><li>Reinforcement learning and real-time optimization algorithms enhance their decision-making abilities.</li></ul><h4>3. Multi-Modal Sensing</h4><ul><li>Integration of sensors for vision, touch, sound, and environmental factors allows robots to perceive and interact with their surroundings effectively.</li></ul><h3>Enabling general purpose robots using LLMS</h3><p>Large Language Models (LLMs) add a new dimension to robotic systems, making them more intuitive, adaptive, and capable of learning. these replace the rules based inference engines of the expert systems with an AI model that can plan and reason.</p><p>While traditional expert systems have limitations (e.g., handling uncertainty, lack of learning) LLMs employ attention mechanisms, which provide insights into the model’s decision-making process.</p><p>LLMs are instrumental in helping robots break down complex goals into sub-tasks. Users can instruct robots without specialized programming knowledge (e.g., “Set the table for dinner”) either via natural language instructions or via visual and or auditory demonstrations.</p><p>Besides interpreting natural language and decomposing them to actionable tasks language models are also used by robots to understand its environment and the changes in it over time .</p><p>The robot adapts to changes in the environment in real-time, continuously updating the model as new sensor data becomes available.it creates a semantic understanding of the objects in the environment to create realistic 3D environments from partial or noisy data helping generate accurate labels for task planning and navigation, allowing robots to distinguish between usable surfaces, hazardous zones, and movable objects.</p><h3>Applications in Robotics</h3><p><strong>Simulation for Training</strong>:</p><ul><li>Virtual environments generated by AI are used to simulate tasks for robot training, enabling faster learning without physical trials.</li></ul><p><strong>Navigation and Path finding</strong>:</p><ul><li>Robots use reconstructed environments to plan safe and efficient routes, avoiding collisions and optimizing movement.</li><li>Generative AI enables predictive modeling, allowing robots to anticipate and navigate around moving objects, such as humans or vehicles.</li></ul><p><strong>Multi-modal understanding</strong></p><ul><li>LLMs integrate textual, visual, auditory, and sensor data to enable more robust decision-making.</li><li>Example: A robot can understand verbal commands, recognize objects visually, and act based on both inputs simultaneously.</li></ul><p><strong>Action Planning</strong>:</p><ul><li>Links sensor data (e.g., depth maps) to language-based plans, improving precision in physical interactions.</li></ul><p><strong>Manipulation and Interaction</strong>:</p><ul><li>Detailed environmental models allow robots to identify and interact with objects with precision, such as picking up fragile items or assembling components.</li><li>AI-generated reconstructions help estimate object properties like texture and material for better handling.</li></ul><h3>Key Advantages of using LLMs in Robotics</h3><ul><li>Improved Human-Robot interaction</li><li>Increased Robot adaptability and flexibility</li><li>Improved Robot learning with sparse data</li><li>Vast pre-trained knowledge that robots can use for on-the-spot problem-solving.</li><li>Update their knowledge dynamically, improving over time.</li><li>Ability to react to unseen tasks and data</li><li>Enhanced decision making and temporal understanding</li></ul><h3>Key Challenges and Future Directions</h3><ul><li>Addressing hardware limitations like energy efficiency and processing power in mobile and edge devices.</li><li>Ensuring adaptability in noisy or variable environments.</li><li>Bridging AI advancements with practical robotics applications to create intuitive, human-aware machines.</li><li>handling noisy or incomplete sensor data, ensuring reliability in reconstructed environments.</li><li>High computational demands of generative models can impact real-time applications.</li><li>Large or highly dynamic environments may challenge the limits of AI model reconstruction accuracy.</li><li>Generative reconstruction requires optimization for energy-efficient processing in mobile robots.</li><li>Training and maintaining LLMs can be costly especially as it requires huge amount of training data</li><li>LLMs tend to hallucinate ie return results that not entirely accurate when they do not have an exact answer for the question asked this may raise safety concerns</li></ul><h3>Is there a solution ? Small language models to the rescue</h3><p>Small Language Models (SLMs) represent an intriguing segment of AI. Unlike their larger counterparts, GPT-4 and LlaMa 2, which boast billions, and sometimes trillions of parameters, SLMs operate on a much smaller scale, typically encompassing thousands to a few million parameters.The smaller model sizes allow small language models to be more efficient, economical, and customizable than their largest counterparts. However, they achieve lower overall capabilities since model capacity in language models has been shown to correlate with size. Determining optimal model size for real-world applications involves navigating the tradeoffs between flexibility &amp; customizability and sheer model performance. There are several reasons why lesser-sized language models fit into the equation of language models.</p><p>The answer lies in the training methods. Different techniques like transfer learning allow smaller models to leverage pre-existing knowledge, making them more adaptable and efficient for specific tasks.For example, a healthcare-specific SLM might outperform a general-purpose LLM in understanding medical terminology and making accurate diagnoses.</p><p>Despite these advantages, it’s essential to remember that the effectiveness of an SLM largely depends on its training and fine-tuning process, as well as the specific task it’s designed to handle. Thus, while lesser-sized language models can outperform LLMs in certain scenarios, they may not always be the best choice for every application.</p><p>Understanding the differences between Large Language Models (LLMs) and Small Language Models (SLMs) is crucial for selecting the most suitable model for various applications. While LLMs offer advanced capabilities and excel in complex tasks, SLMs provide a more efficient and accessible solution, particularly for resource-limited environments. Both models contribute to the diverse landscape of AI Applications each with strengths and potential impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*yeU4bKn00uG0p58SiDbX0Q.png" /></figure><p>By processing data locally and reducing reliance on cloud infrastructure, edge computing with SLMs enables faster response times, improved data privacy, and enhanced user experiences. This decentralized approach to AI has the potential to transform the way businesses and consumers interact with technology, creating more personalized and intuitive experiences in the real world. As LLMs face challenges related to computational resources and potentially hit performance plateaus, the rise of SLMs promises to keep the AI ecosystem evolving at an impressive pace. Training methodologies, dataset distribution and hyper parameter optimization are huge factors Fine tuning when done right helps immensely. Something like Mythomax or Orca are great examples of fine tuning done right. Training from scratch gives you fine-grained control over every aspect of the training process, including hyperparameters, optimization techniques, and data augmentation strategies. This level of control can be advantageous when optimizing for specific performance metrics or conducting research experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*JU7TRoOJEr5LUaA7q1AbjQ.png" /></figure><p>Using your own data could also lead to superior performance, potentially giving you a competitive advantage. You can also decide exactly what content filters to use based on your specific business use case. For example, you might need a longer sequence length than what a commercial model offers or the ability to add specific content filters to your training data. When you opt to use a commercial LLM, you have to work around the sequence limits and have no visibility of the data used for training.</p><p>Running small language models (SLMs) offline on mobile phones enhances privacy, reduces latency, and promotes access. Users can interact with llm-based applications, receive critical information, and perform tasks even in offline environments, ensuring accessibility and control over personal data. Real-time performance and independence from centralized infrastructure unlock new opportunities for innovation in mobile computing, offering a seamless and responsive user experience. However, running SLMs offline on mobile phones presents several challenges due to the constraints of mobile hardware and the complexities of running LLM tasks. Here are some key challenges:</p><ol><li><strong>Limited Processing Power:</strong> Mobile devices, especially smartphones, have limited computational resources compared to desktop computers or servers. SLMs often require significant processing power to execute tasks such as text generation or sentiment analysis, which can strain the capabilities of mobile CPUs and GPUs.</li><li><strong>Memory Constraints:</strong> SLMs typically require a significant amount of memory to store model parameters and intermediate computations. Mobile devices have limited RAM compared to desktops or servers, making it challenging to load and run large language models efficiently.</li><li><strong>Battery Life Concerns:</strong> Running resource-intensive tasks like NLP on mobile devices can drain battery life quickly. Optimizing SLMs for energy efficiency is crucial to ensure that offline usage remains practical without significantly impacting battery performance.</li><li><strong>Storage Limitations:</strong> Storing large language models on mobile devices can be problematic due to limited storage space. Balancing the size of the model with the available storage capacity while maintaining performance is a significant challenge.</li><li><strong>Update and Maintenance:</strong> Keeping SLMs up to date with the latest improvements and security patches presents challenges for offline deployment on mobile devices. Ensuring seamless updates while minimizing data usage and user inconvenience requires careful planning and implementation.</li><li><strong>Real-Time Performance:</strong> Users expect responsive performance from mobile applications, even when running complex NLP tasks offline. Optimizing SLMs for real-time inference on mobile devices is crucial to provide a smooth user experience.</li></ol><h3>Required Models</h3><p><strong>Planning</strong></p><ol><li>Navigation planning</li><li>Task and action planning</li></ol><p><strong>Perception</strong></p><ol><li>Video classification model</li><li>Image classification model</li><li>Pan optic segmentation model</li><li>Real time depth and angle perception</li><li>Sensor data (time series) prediction model</li></ol><p><strong>Perception and control</strong></p><ol><li>Action prediction model</li><li>Motion prediction model</li></ol><p>At <strong>Monkeypatched</strong>, we specialize in integrating <strong>Large Language Models (LLMs)</strong> into the world of <strong>robotics</strong>, revolutionizing how robots perceive, interpret, and interact with the world. With cutting-edge innovation and a commitment to excellence, we enable seamless human-robot collaboration and smarter automation. with a vision of building <strong>general-purpose humanoids</strong> designed for a wide range of <strong>industrial tasks</strong>. Our solutions bring intelligence, adaptability, and efficiency to industries, enabling smarter automation and seamless human-robot collaboration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eab9d3a74ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>