πΌ AI Engineer.
Compiling real-time the race towards AGI π.
Follow to stay at bleeding edge AI π
Subscribe to my Newsletter β https://t.co/Jfj0r0wLUN
3 subscribers
Nov 1 β’ 5 tweets β’ 3 min read
Not all brain cells are equal - same goes for LLM attention heads! π‘
Why store everything when you can just remember the important stuff?
Smart KV cache compression that knows which attention heads matter most.
Hence, HeadKV intelligently compresses LLM memory by identifying and prioritizing crucial attention heads
π― Original Problem:
KV caching in LLMs faces significant memory overhead with increasing input length. Current compression methods operate at layer-level, missing the opportunity to optimize at individual attention head level.
-----
π§ Solution in this Paper:
β’ HeadKV: Compresses KV cache at individual head level instead of layer level
β’ Allocates cache budgets based on head importance using Needle-in-a-Haystack tests
β’ HeadKV-R2: Enhanced version that evaluates both retrieval and reasoning abilities
β’ Uses dynamic budget allocation across heads based on importance scores
β’ Retains most relevant KV cache entries within each head using attention-based selection
-----
π‘ Key Insights:
β’ Not all attention heads are equally important for text generation
β’ Head-level compression outperforms layer-level approaches
β’ Combining retrieval and reasoning abilities for importance scoring is crucial
β’ Dynamic budget allocation across heads is more effective than fixed allocation
β’ Just 1.5% of KV cache can retain 97% of full performance
-----
π Results:
β’ Achieves 97% of full KV cache performance while retaining only 1.5% of cache
β’ Outperforms baselines on LongBench and LooGLE benchmarks
β’ Superior performance in low-resource settings (KV size = 64 & 128)
β’ Maintains computational efficiency comparable to existing approaches
β’ Effective preservation of both retrieval and reasoning capabilities
π The method operates in two key steps: First, it estimates head importance scores using Needle-in-a-Haystack tests that evaluate both retrieval and reasoning abilities.
Second, it allocates KV cache budgets to individual heads based on their importance scores, with more important heads receiving larger cache allocations.
Oct 28 β’ 4 tweets β’ 2 min read
GenAI implementation poses a series of hurdles to overcome.
Vector DBs, data processing pipelines, embedding models, deployment systems, and monitoring tools and many more.
All these create significant engineering complexity.
A 𧡠1/n
So if I have a all-in-one GenAI development toolkit operating on owned infrastructure, that would eliminate all these unnecessary pressure and stumbling blocks from implementing a new GenAI project.
And then I found such a solution: @DynamiqAGI β¨
And what's great is that it is open-source with Apache 2 License.
So Dynamiq simplifies my AI-powered solution development cycle significantly.
It handles Multi-agent orchestration and Retrieval-Augmented Generation (RAG) integration with a comprehensive toolkit.
Core capabilities: π¨βπ§
-> Agent orchestration: Single and multi-agent workflow support
-> RAG toolkit: Vector DB integration, chunking, pre-processing, reranking
-> DAG workflow control: Parallel execution, retries, error handling
-> Custom validators: Configurable validation rules for workflows
-> Multi-modal integration: Support for Vision-Language Models (VLMs)
Also good for scalability, from prototype to enterprise.
𧡠2/n
Here's a simple example to get you started with @DynamiqAGI :
Oct 26 β’ 8 tweets β’ 2 min read
MIT's "Mathematics for Computer Science".
A 1048 page available for Free.
Focuses on explaining the use of mathematical models and methods to analyze problems in computer science.
Oct 15 β’ 5 tweets β’ 2 min read
Agent S uses a computer like a human to solve diverse desktop tasks on different systems.
Experience-augmented hierarchical planning enables Agent S to handle diverse GUI tasks with improved performance.
**The original Problem** π―:
Automating complex computer tasks presents challenges in acquiring domain-specific knowledge, planning over long task horizons, and handling dynamic interfaces.
-----
**Solution in this Paper** π οΈ:
β’ Experience-augmented hierarchical planning:
- Manager module for task decomposition
- Worker modules for subtask execution
- Self-evaluator for experience summarization
β’ Agent-Computer Interface (ACI):
- Dual-input strategy for visual understanding and element grounding
- Bounded action space of language-based primitives
β’ Continual memory update mechanism for ongoing learning
-----
**Key Insights from this Paper** π‘:
β’ Combining external knowledge and internal experience enhances task planning
β’ Structured interface improves MLLM reasoning for GUI control
β’ Hierarchical planning supports long-horizon workflows
β’ Continual learning enables adaptation to new tasks and environments
-----
**Results** π:
β’ OSWorld benchmark: 20.58% success rate (83.6% relative improvement over baseline)
β’ Consistent improvements across five computer task categories
β’ WindowsAgentArena: 18.2% success rate (36.8% improvement without adaptation)
β’ Ablation studies confirm effectiveness of individual components
π€ Agent S addresses three main challenges in automating computer tasks:
1. Acquiring domain-specific knowledge for diverse applications 2. Planning over long task horizons 3. Handling dynamic, non-uniform interfaces
Oct 9 β’ 4 tweets β’ 3 min read
Brilliant Paper from @Microsoft. π
"DIFFERENTIAL TRANSFORMER" β¨
DIFF Transformer cancels attention noise, enhancing key information retrieval and reducing hallucination in large language models.
β’ 30% accuracy improvement in key information retrieval with 64K context
β’ 10-20% accuracy gain in many-shot in-context learning across datasets
β’ 7-11% reduction in hallucination for summarization and question answering
β’ Maintains performance with 6-bit quantization, while Transformer degrades significantly
**Original Problem** π:
Transformer tends to overallocate attention to irrelevant context, leading to challenges in accurately retrieving key information.
-----
**Solution in this Paper** π‘:
β’ Introduces DIFF Transformer with differential attention mechanism
β’ Calculates attention scores as difference between two separate softmax attention maps
β’ Subtraction cancels noise, promoting emergence of sparse attention patterns
β’ Amplifies attention to relevant context while reducing attention to irrelevant parts
β’ Uses GroupNorm to normalize each attention head independently
-----
**Key Insights from this Paper** π‘:
β’ DIFF Transformer outperforms Transformer in scaling model size and training tokens
β’ Requires only ~65% of model size or training tokens to match Transformer performance
β’ Excels in long-context modeling, key information retrieval, and in-context learning
β’ Mitigates hallucination in question answering and text summarization
β’ Reduces outliers in model activations, enabling better quantization
Transformer often over-attends to irrelevant context (i.e., attention noise). DIFF Transformer amplifies attention to answer spans and cancels noise, enhancing the capability of context modeling.
Oct 6 β’ 5 tweets β’ 2 min read
"claude 3.5 sonnet to outperform openai o1 in terms of reasoning" with prompting π€
----
Prompt from the article:
Begin by enclosing all thoughts within tags, exploring multiple angles and approaches.
Break down the solution into clear steps within tags. Start with a 20-step budget, requesting more for complex problems if needed.
Use tags after each step to show the remaining budget. Stop when reaching 0.
Continuously adjust your reasoning based on intermediate results and reflections, adapting your strategy as you progress.
Regularly evaluate progress using tags. Be critical and honest about your ..........
........"
Sep 25 β’ 4 tweets β’ 5 min read
MotleyCrew: a pragmatic approach to AI agents
AI agents are all the rage these days. An AI agent is simply a wrapper around a Large Language Model (LLM) that allows it to request actions, such as a web search, from the outside world, and feed the results back to the LLM, and so on until a desired outcome is achieved.
π¨βπ§ As each agent can handle only so many different instructions at once in its prompt, often it is helpful to use a team of multiple agents for a task, just like a team of humans divides a task among themselves.
Then the question arises: how should the agents coordinate their work? π€
A thread π§΅1/n π
Many existing solutions and frameworks assume the user will use that particular framework's agent implementation as well as its way of coordinating agent interactions.
That is an important limitation: building good agents is hard, and so is creating good agent communication semantics.
As building good agents is a difficult task that is distinct from multi-agent orchestration, itβs unlikely that a single framework would have both the best agents and the best multi-agent communication layer.
And then I stumbled upon this Open-source project - MotleyCrew. π‘
We canβt simply assume that the framework that excels at one will also excel at the other.
So that was the starting point for @motleycrew_ai providing wrappers to all the above frameworksβ agents, and focussing on making their interaction as simple and powerful as possible.
πThus, for example, in MotleyCrew you can directly pass agents as tools to other agents (without introducing an additional βdelegationβ concept with its own semantics), and these, in turn, can have other agents as tools, and so on.
πAnother MotleyCrew feature, output handlers, is a simple way of implementing the writer-critic pattern, and to provide user-specified guarantees about an agentβs output.
πThis works as follows: the agent is told (under the hood) that it has to return its final result only via the output handler. The output handler runs any verification logic the user specifies, and if that fails, tells the agent what failed and asks it to try again, until success. If successful, the output handlerβs output is returned as the agentβs output.
πThis pattern takes the reliability of AI agents to a whole new level: the output handler can contain both algorithmic logic (for example, verifying that all the links contained in the agent input are also contained in the output) and agentic logic (for example, criticising the writing style, or double-checking that the output fulfils the instructions given to the agent), or any combination.
π§΅2/n
π MotleyCrew doesn't try to reinvent the wheel or build its own little walled garden with its own implementation of every component needed in a multi-agent system.
π On the contrary, if you want to combine RAG from LlamaIndex with a group chat from Autogen, and make them nodes in a complex LangGraph structure, with a couple of CrewAI tools thrown in somewhere, the framework makes it easy for you.
π Beyond combining other frameworks, @motleycrew_ai also adds some other features that have proven to be useful in practice, such as an embedded knowledge graph that can be used for structuring the knowledge the agents create, as well as an ability for agents to create tasks for each other using that knowledge graph.
Small but extremely useful features are the ability to let tools see their agent's input, and to force agents to only return a final result through a tool - thus guaranteeing a level of output quality that is hard to achieve otherwise.
Sep 14 β’ 4 tweets β’ 1 min read
The biggest contribution of OpenAI Strawberry (o1) π is on inference scaling.
Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters.
The entire result-search space becomes a mini dataset of training examples
Is this a Vacuum-Tube to Silicon Transistor moment for LLM if true ? π€―
Published in Nature yesterday.
β¨ Molecular memristors enable 14-bit analog computing, surpassing digital efficiency for core matrix operations.
The Paper achieved >73 dB signal-to-noise-ratio, a four-order of magnitude improvement over the SOTA 10-12, while consuming 460X less energy than digital computers13
**Original Problem** π:
Vector-matrix multiplication (VMM) is computationally expensive, requiring n^2 steps for vectors of length n. Current dot-product engines (DPEs) for VMM have low precision (2-6 bits) due to non-idealities in analog circuit elements.
-----
**Key Insights from this Paper** π‘:
β’ Developed 14-bit precision molecular memristor crossbar for VMM
β’ Supramolecular electronics yield unprecedented precision in neuromorphic hardware for AI acceleration.
β’ Achieved linear, symmetric weight updates with 16,520 distinct analog levels
β’ Enabled one-step programmability of conductance levels
β’ Implemented selector-free crossbar design using unidirectional elements
-----
**Solution in this Paper** π§ͺ:
β’ Fabricated 64x64 crossbar using [Ru^II L_2](BF_4)_2 molecular film
β’ Engineered symmetric potentiation/depression characteristics
β’ Utilized supramolecular electronic transitions between 31 and 22 states
β’ Implemented custom >16-bit precision CMOS peripheral circuit
β’ Compensated for wire resistances and parasitic effects
-----
**Results** π:
β’ 16,520 distinct analog levels with 14-bit resolution
β’ Signal-to-noise ratio of 73-79 dB for VMM operations
β’ 4 orders of magnitude improvement in precision over state-of-the-art
β’ 460x higher energy efficiency than CPU for matrix operations
β’ Demonstrated high-fidelity image reconstruction via inverse Fourier transform
π Published in Nature -
The common retrievers like DPR (Dense Passage Retrieval) normally work with 100-word Wikipedia paragraphs. π€
π‘ This paper proposes LongRAG - processes the entire Wikipedia into 4K-token units, 30x longer than before π₯
By increasing the unit size, they significantly reduce the total units from 22M to 600K. This significantly lowers the burden of retriever, which leads to a remarkable retrieval score: answer recall@1=71% on NQ (previously 52%) and answer recall@2=72% (previously 47%) on HotpotQA (full-wiki).
This technique is particularly beneficial for open-domain question answering, where detailed and accurate responses are crucial. By leveraging external information, RAG systems can overcome the limitations of relying solely on the parametric knowledge embedded in LLMs, making them more effective in handling complex queries.
π Challenges for regular RAG π
Traditional RAG frameworks often use short retrieval units, such as 100-word passages, requiring the retriever to sift through large amounts of data. This design burdens the retriever heavily while the reader's task remains relatively simple, leading to inefficiencies and potential semantic incompleteness due to document truncation.
π‘ And so her comes LongRAG
To address these challenges, this LongRAG framework comprises a "long retriever" and a "long reader" component, designed to process longer retrieval units of around 4K tokens each.
By increasing the size of the retrieval units, LongRAG reduces the number of units from 22 million to 600,000, significantly easing the retriever's workload and improving retrieval scores. This innovative approach allows the retriever to handle more comprehensive information units, enhancing the system's efficiency and accuracy.
β¨ How it works π
π Retrieval unit selection impacts performance. Passage-level units have a turning point between 100-200, document-level between 5-10, and grouped documents between 4-8. Optimal context length for the reader is around 30K tokens.
π Semantic integrity of retrieval units is crucial. Longer, more complete units outperform shorter, fragmented ones.
π LongRAG approximates similarity scores between queries and long retrieval units by maximizing scores between the query and all chunks within the unit. This outperforms direct encoding of entire long contexts.
π The framework uses a two-turn approach for answer extraction: 1) Generate a longer answer (few words to sentences) from retrieved context. 2) Extract a concise short answer (few words) using in-context examples.
π The LongRAG framework operates by grouping related documents into long retrieval units, which the long retriever then processes to identify relevant information.
To extract the final answers, the retriever filters the top 4 to 8 units, concatenated and fed into a long-context LLM, such as Gemini-1.5-Pro or GPT-4o. This method leverages the advanced capabilities of long-context models to process large amounts of text efficiently, ensuring a thorough and accurate extraction of information.
π Performance π
- On the Natural Questions (NQ) dataset, it achieved an exact match (EM) score of 62.7%, a significant leap forward compared to traditional methods. On the HotpotQA dataset, it reached an EM score of 64.3%.
So it matches the performance of state-of-the-art fine-tuned RAG models.
The framework reduced the corpus size by up to 30 times and improved the answer recall by approximately 20 percentage points compared to traditional methods, with an answer recall@1 score of 71% on NQ and 72% on HotpotQA.
ποΈ Paper - arxiv.org/pdf/2406.15319β¦
Sep 2 β’ 4 tweets β’ 3 min read
Useful Prompting technique.
Simply ask the LLM to re-read the question - significantly boosts LLM reasoning across diverse tasks and model types. π‘
Repeats question input twice in prompt, unlocks latent reasoning potential
**Problem** π€:
Decoder-only LLMs with unidirectional attention struggle with nuanced reasoning tasks due to limited global understanding of input questions.
**Key Insights from this Paper π‘**:
β’ Re-reading (RE2) input enhances reasoning by improving question comprehension
β’ Enables "bidirectional" understanding in unidirectional LLMs
β’ Compatible with existing thought-eliciting prompting methods
β’ Effective across various LLM types and reasoning tasks
**Solution in this Paper** π:
β’ Introduces RE2 (Re-Reading) prompting method:
- Repeats question input twice in prompt
- Enhances input understanding before reasoning
- Allows tokens to attend to full context in second pass
β’ Compatible with Chain-of-Thought and other prompting techniques
β’ Applicable to zero-shot, few-shot, and self-consistency settings
**Results** π:
β’ Consistent improvements across 14 datasets and 112 experiments
β’ Effective for both instruction-tuned (ChatGPT) and non-tuned (LLaMA) models
β’ Increases n-gram recall between generation and input question
β’ Most effective when reading question twice
Example inputs of CoT prompting versus CoT prompting with RE2.
RE2 is a simple prompting method that repeats the question as input.
Typically, tokens in the question, such as "tennis balls", cannot see subsequent tokens in the original setup for LLMs (the top figure).
In contrast, LLMs with RE 2 allows "tennis balls" in the second pass to see the entire question containing "How many ...", achieving an effect of a "bidirectional" understanding (the bottom figure).
Aug 16 β’ 6 tweets β’ 3 min read
I love Self-Calibration Prompting Technique π¨βπ§
π It's a two-step prompting process. Initially, the LLM is prompted to answer a specific question.
Subsequently, a new prompt is generated that includes the original question, the LLM's response, and an additional query asking the LLM to evaluate the correctness of its own answer.
π― This introspective step is designed to assess the confidence level of the response, providing a built-in mechanism for self-evaluation.
Example:
1. Question: What are the current treatment options for Type 2 diabetes?
2. LLMβs Answer: Current treatment options for Type 2 diabetes include lifestyle modifications, oral medications like metformin, and in some cases, insulin therapy.
3. Follow-up Prompt: Reflecting on the latest medical guidelines, is this response accurate and complete?
--------
The concept of Self-Calibration came from the paper "Language Models (Mostly) Know What They Know"
𧡠2/n
π§ LLMs often struggle with accurately evaluating their own knowledge and capabilities, which can lead to overconfident or unreliable outputs. This paper investigates whether LLMs can be trained to recognize what they do and don't know, and how this ability generalizes across tasks.
This paper investigates whether LLMs can accurately evaluate their own knowledge and capabilities, concluding that larger models demonstrate improved calibration and self-evaluation across diverse tasks.
Aug 15 β’ 9 tweets β’ 7 min read
What you see here is a disruptive open/distributed AI tech.
More network of nodes Is All You Need π‘
I am so intrigued
𧡠1/n - A long thread π
Here a Language Model is running on someone else's machine, for free, no API needed. π€―
π A swarm of agents running intelligently on a distributed network of nodes and making use of the fastest AI infrastructure and the most powerful open models.
This is @HyperspaceAI - where they were able to get GPT-4 comparable results using a complex distributed system spanning 100+ models with local consumer devices.
With 17,745+ unique nodes and 100+ models already on the network you can serve LLMs today. This is a growth of 100 to 18,000 nodes in 10 months. During the same period, they also overcame scalability issues, and rebuilt for 1M+ node support.
---
β¨ Below are some features that are in the pipeline and will be supported very soon.
- Embedding models, re-rankers, vectors, and more to other consumers and developers coming soon.
- Points-based incentives rolling out soon. A novel Proof-of-FLOPS system that sends a matrix multiplication challenge to your device based on the VRAM pledged and rewards nodes accordingly, in addition to improving the reliability of the network - soon to be supported.
---
And @HyperspaceAI just launched the web version at node.hyper .space
So you can join the world's fastest-growing P2P AI network in multiple ways π
π: Join using just a web browser
π»: Join using a client on your desktop or laptop
π±: Join using a browser on your smartphone
π₯οΈ: Join using just the command line or a server
𧡠2/n
The concept itself isn't new, but what's reignited interest is the recent announcement from @cohere regarding their support for int8 and binary embeddings in their Cohere embed v3.
π First, in essence, embeddings are numerical representations of more complex objects, like text, images, audio, etc. Specifically, the objects are represented as n-dimensional vectors.
After transforming the complex objects, you can determine their similarity by calculating the similarity of the respective embeddings! This is crucial for many use cases: it serves as the backbone for recommendation systems, retrieval, one-shot or few-shot learning, outlier detection, similarity search, paraphrase detection, clustering, classification, and much more.
-------
π Binary Quantization for embeddings
Unlike quantization in models where you reduce the precision of weights, quantization for embeddings refers to a post-processing step for the embeddings themselves. In particular, binary quantization refers to the conversion of the float32 values in an embedding to 1-bit values, resulting in a 32x reduction in memory and storage usage.
--------
β¨ Binary quantization example
Vector embeddings are usually generated by embedding models, such as Cohereβs embed v3, and a single vector embeddings will in the following form.
[0.056, -0.128, -0.029, 0.047, β¦, 0.135]
To quantize float32 embeddings to binary, we simply threshold normalized embeddings at 0
That is, because these embeddings have very small absolute numbers close to zero, you can turn them into a binary vector:
1: If the value is greater or equal to 0.
0: If the value is smaller than 0.
So that you get something like this.
[1, 0, 0, β¦, 1]
𧡠2/n
π So basically why does binary quantization reduce vector embedding size so much?
It's kind of like turning a colored image into a black and white image.
By converting the floating point numbers, which are stored in 32 bits, into a single bit, you only need 1/32nd of memory space to store a binarized vector. This can lead to increased search speed and reduced storage costs.
And because vector embeddings are usually high-dimensional, you can still get meaningful similarity measures for vector search. π€―
β¨ Now the question is how to calculate the similarity of vectors which has been binarized ?
π We can use the Hamming Distance to efficiently perform retrieval with these binary embeddings. This is simply the number of positions at which the bits of two binary embeddings differ. The lower the Hamming Distance, the closer the embeddings, and thus the more relevant the document. A huge advantage of the Hamming Distance is that it can be easily calculated with 2 CPU cycles, allowing for blazingly fast performance.
Jul 8 β’ 10 tweets β’ 4 min read
Incredible results for the RAG world from @nvidia model π. Llama3-RankRAG from @nvidia significantly outperforms GPT-4 models on 9 knowledge-intensive benchmarks. π€―
π Performs comparably to GPT-4 on 5 RAG benchmarks in the biomedical domain without instruction fine-tuning on biomedical data, demonstrating its superb capability for generalization to new domains. π€―
The secret is a novel instruction fine-tuning framework, named RankRAG π¨βπ§
Llama3-RankRAG-8B and Llama3-RankRAG-70B outperforms Llama3-ChatQA-1.5-8B and Llama3-ChatQA-1.5-70B by a margin, respectively. π₯
The problem with traditional RAG was that LLM typically utilize the top-k contexts from a retriever.
This led to suboptimal performance, especially when dealing with a large number of retrieved passages or when initial retrieval results were poor.
The key question this paper addresses is how to unify context ranking and answer generation within a single LLM for more effective RAG. The researchers conclude that their proposed RankRAG method significantly outperforms existing approaches by instruction-tuning an LLM for both ranking and generation tasks.
π RankRAG instruction-tunes a single LLM for dual purposes: context ranking and answer generation in RAG. This unified approach allows the model to excel at both tasks simultaneously. The process incorporates a small fraction of ranking data (about 50k examples) alongside other task-specific datasets. Yields superior ranking performance compared to models trained on much larger ranking datasets.
π RankRAG uses a retrieve-rerank-generate pipeline. The LLM first reranks the top-N retrieved contexts, then generates answers based on the refined top-k contexts.
π The training blend for RankRAG includes context-rich QA data, retrieval-augmented QA data, context ranking data, and retrieval-augmented ranking data. This diverse mix enhances the model's ability to handle various RAG scenarios.
π The method addresses the trade-off between recall and precision in context selection. By incorporating ranking, RankRAG can effectively use a smaller number of highly relevant contexts (e.g., top-5) while maintaining or improving performance.
π RankRAG's ranking capability transfers well across different retrievers and generalizes to unseen domains, showcasing its robustness and adaptability.
π Current RAG systems use limited retrievers (e.g. BM25, BERT) for efficiency, compromising relevance estimation accuracy.
π There's a trade-off in selecting top-k contexts: small k misses information, large k introduces noise.
π Performance often plateaus around k=10, as shown with ChatQA-1.5.
π These limitations motivate RankRAG's approach of integrating ranking into the LLM itself.
Jun 30 β’ 7 tweets β’ 4 min read
Another 'WOW' paper - Upto 20x improvement in inference throughput with Block Transformer compared to vanilla transformers with equivalent perplexity.π€―
How β by MASSIVELY reducing KV cache IO overhead from quadratic to linear with respect to context length, solving a key challenge in scaling to very long contexts and also novel application of global-to-local modeling. π€―
Paper - "Block Transformer: Global-to-Local Language Modeling for Fast Inference":
π Block Transformers can also be uptrained from pretrained vanilla models, closely approaching the performance of those pretrained from scratch, using just 10% of the training budget.
π adopts a hierarchical global-to-local modeling approach. It isolates the expensive bottlenecks of global modeling to lower layers and applies fast local modeling in upper layers. This is achieved through three components:
1. Embedder: aggregates each block of L_B input tokens into an input block embedding. i.e. L_B represents the block length, which is the number of tokens aggregated into a single block.
2. Block decoder: an autoregressive transformer that applies self-attention between blocks to decode a context block embedding for predicting the next block.
3. Token decoder: autoregressively decodes the token contents of the next block, applying local self-attention between only the L_B tokens within the block.
π The block decoder reduces overall costs through its coarse granularity. It mitigates the quadratic costs of self-attention by using coarse-grained block inputs instead of individual tokens, reducing context length by L_B. This reduces FLOPs for positionwise computations by L_B and attention score computation by L_B^2. KV cache usage and KV cache IO are also reduced by L_B and L_B^2 respectively.
π The token decoder nearly eliminates the costs of attention as there is no need to compute, store, and retrieve KV-cache of past tokens beyond the small local context of L_B tokens. It eliminates prefill (necessary only in the block decoder) and reduces KV cache IO from quadratic to linear with respect to context length. This allows for significantly higher compute unit utilization.
π To incorporate the context embedding and leverage the low-cost compute in the token decoder, the context block embedding is projected into prefix tokens. This enables further refinement of the global context and allows increasing computational width of the token decoder by extending the prefix length.
Hierarchical global-to-local architectures have shown significant potential to effectively model large-scale data by addressing global dependencies in coarse detail and capturing fine details within local regions.
Jun 30 β’ 5 tweets β’ 2 min read
LLMs are highly sensitive to prompt variations, leading to inconsistent performance across different prompts for the same task. π¨βπ§
Intent-based Prompt Calibration (IPC) iteratively refines prompts to match user intent using synthetic boundary cases, addressing prompt sensitivity and optimizing with limited data.
π IPC generates challenging synthetic samples at each iteration, focusing on boundary cases that expose prompt ambiguities.
π The system employs three meta-prompts: Sample Generator, Analyzer, and Prompt Generator. The Sample Generator creates diverse, adversarial samples with balanced class distribution. The Analyzer evaluates prompt performance and identifies failure cases. The Prompt Generator suggests improved prompts based on historical performance and analysis.
π For generative tasks, IPC first calibrates a ranking prompt, then uses it to optimize the generative prompt. This approach allows optimization with minimal annotation effort.
π The system architecture consists of four components: Dataset (manages data operations), Estimator (handles predictions and annotations), Evaluator (assesses records and performs error analysis), and Optimizer (manages the optimization process flow).
π IPC outperforms existing methods like OPRO and PE on classification tasks (spoiler detection, sentiment analysis, PG detection) and generative tasks (enthusiastic/reliable and sarcastic/positive movie reviews).
π The method demonstrates superior performance with limited data, achieving higher accuracy and lower variance compared to baseline approaches.
π Ablation studies reveal the importance of synthetic data generation, iterative refinement, and error analysis in improving model performance.
π IPC effectively handles imbalanced data distributions by generating balanced synthetic samples, particularly beneficial for real-world moderation tasks.
Jun 30 β’ 6 tweets β’ 3 min read
A very intriguing recent paper "Nested Jailbreak Prompts can Fool LLMs Easily" - reveals the inadequacy of current defense methods in safeguarding LLMs.
Generalizes jailbreak prompt attacks into two aspects:
(1) Prompt Rewriting and (2) Scenario Nesting.
π Propose ReNeLLM, an automatic framework that leverages LLMs themselves to generate effective jailbreak prompts. Sgnificantly improves the attack success rate while greatly reducing the time cost compared to existing baselines. Our study also reveals the inadequacy of current defense methods in safeguarding LLMs.
π ReNeLLM framework introduced, generalizing jailbreak prompt attacks into prompt rewriting and scenario nesting. Prompt rewriting involves operations like paraphrasing, altering sentence structure, misspelling sensitive words, inserting meaningless characters, partial translation, and changing expression style. These operations preserve semantic meaning while disguising harmful intent.
π Scenario nesting embeds rewritten prompts into task scenarios like code completion, text continuation, and table filling. This leverages LLMs' instruction-following capabilities to bypass safety alignments. Scenarios chosen align with training data, shift attention, and leave blanks for completion.
π Automated process uses LLMs to generate and evaluate jailbreak prompts. GPT-3.5 performs rewriting and harmfulness evaluation. Nested prompts fed to target LLM (e.g. Claude-2) for response. Success determined by harmful output generation.
π ReNeLLM achieves state-of-the-art attack success rates (ASR) across open and closed-source LLMs. For Claude-2, ReNeLLM attains 69.6% GPT-ASR compared to 0% for baselines. Time cost reduced by 76.61% vs GCG and 86.19% vs AutoDAN.
π Attention visualization reveals LLMs' priority shift from balancing external/internal instructions to favoring external ones after rewriting/nesting. This explains jailbreak success and informs potential defenses.
π Defense strategies explored: incorporating priority prompts (e.g. "prioritize safety"), enhancing safety through supervised fine-tuning, and using harmfulness classifiers. Results show trade-offs between safety and performance, highlighting challenges in developing robust defenses.
Jun 29 β’ 9 tweets β’ 3 min read
This 76-page paper on Prompting Techniques has become quite popular. A nice read for your weekend.
- "The Prompt Report: A Systematic Survey of Prompting Techniques": β¨
Explores structured understanding and taxonomy of 58 text-only prompting techniques, and 40 techniques for other modalities.
π The paper focuses on discrete prefix prompts rather than cloze prompts, because prefix prompts are widely used with modern LLM architectures like decoder-only models. It excludes soft prompts and techniques using gradient-based updates.
π The paper identifies 58 text-based prompting techniques broken into 6 major categories:
1) In-Context Learning (ICL) - learning from exemplars/instructions in the prompt 2) Zero-Shot - prompting without exemplars 3) Thought Generation - prompting the LLM to articulate reasoning 4) Decomposition - breaking down complex problems 5) Ensembling - using multiple prompts and aggregating outputs 6) Self-Criticism - having the LLM critique its own outputs
π For ICL, it discusses key design decisions like exemplar quantity, ordering, label quality, format, and similarity that critically influence output quality. It also covers ICL techniques like K-Nearest Neighbor exemplar selection.
π Extends the taxonomy to multilingual prompts, discussing techniques like translate-first prompting and cross-lingual ICL. It also covers multimodal prompts spanning image, audio, video, segmentation, and 3D modalities.
π More complex techniques like agents that access external tools, code generation, and retrieval augmented generation are also taxonomized. Evaluation techniques using LLMs are discussed.
π Prompting issues like security (prompt hacking), overconfidence, biases, and ambiguity are highlighted. Two case studies - benchmarking techniques on MMLU and an entrapment detection prompt engineering exercise - are presented.
Jun 28 β’ 7 tweets β’ 4 min read
Activation Beacon is such a classic paper from Jan-2024
"Soaring from 4K to 400K: Extending LLM's Context with Activation Beacon"
Can be a revolutionary paper if implementable for all cases - for massively increasing the context window of LLMs
Authors trained LLaMA-2 for 10K-steps with 4K context window and then it generalized to 400K context window π₯
πKey technique is to condenses LLM's raw activations into more compact forms such that it can perceive a much longer context with a limited context window. Activation Beacon is introduced as a plug-and-play module for the LLM.
π "It fully preserves the LLM's original capability on short contexts while extending the new capability on processing longer contexts. Besides, it works with short sliding windows to process the long context, which achieves a competitive memory and time efficiency in both training and inference. "
π "Activation Beacon is learned by the auto-regression task conditioned on a mixture of beacons with diversified condensing ratios. Thanks to such a treatment, it can be efficiently trained purely with short-sequence data in just 10K steps, which consumes less than 9 hours on a single 8xA800 GPU machine."
π "The experimental studies show that Activation Beacon is able to extend Llama-2-7B's context length by Γ100 times (from 4K to 400K), meanwhile achieving a superior result on both long-context generation and understanding tasks. Our model and code will be available at the BGE repository."
A relevant question here, that automatically comes to mind - 'How does the quality of retrieval change over context length β
And we can refer to this paper for understanding that aspect.
Paper - ''Training-Free Long-Context Scaling of Large Language Models'
This paper shows that existing long-context LLMs, which have already supported a 32k context window, can further extrapolate to a 192k context length while maintaining high passkey retrieval accuracy and low perplexity.arxiv.org/abs/2402.17463
Jun 23 β’ 7 tweets β’ 4 min read
Sliding Window Attention is such a brilliant idea π‘
And it was one of the secret sauces behind the legendary Mistral-7B, which enabled it to handle 100k+ token sequences with linear (ish) complexity.
A long thread π§΅1/n
---
π Most Transformers use Vanilla Attention, where each token in the sequence can attend to itself and all the tokens in the past.
π So the memory increases linearly with the number of tokens. Hence the problem of higher latency during inference time and smaller throughput due to reduced cache availability.
π Sliding Window Attention (SWA) can alleviate those problems and can handle longer sequences of tokens more effectively at a reduced computational cost.
So standard, decoder-only, causal LMs (like the whole GPT series), each token can "attend to" (i.e. "look at") every token that has come before it.
In Sliding Window Attention, earlier layers have a narrower view of history, and this progressively builds up the deeper you go into the model.
----
π Performance implications of sliding window attention:
Computational complexity: O(n * w) where n is sequence length, w is window size
Memory usage: O(w) instead of O(n) for full attention
Information retention: Local context preserved, global context approximated
----
π Because SWA exploits the stacked attention layers to attend information beyond the window size W.
π Each hidden state h in position i of layer k can attend to all hidden states from the previous layer with position between i-W and i. Where `W` is the "Window Size"
π This holds for all hidden states. Thus, recursively, a hidden state can access tokens from the input layer at a distance of W x k tokens. With 32 layers and a window size of 4096, this model has an attention span of 131k tokens.
----
π Limitations of Sliding Window Attention
Lack of Global Context β Because Sliding Window Attention operates on fixed windows, it may not be able to capture long-range dependencies that span across multiple windows. This can limit the model's ability to understand the global context of the input sequence.
π Example, if prompt/instruction text is 16K but Sliding Window Attention's sliding window is only 4K, it may cause my instructions to get ignored, as the window moved to the last 4K of those 16K and will "un-attend" my instructions at the beginning of those 16K.
----------
π Global Attention, in contrast, considers the entire input sequence at once, applying attention to all positions simultaneously. It focuses on specific, strategically chosen locations to capture the most relevant information, ensuring that each token with global attention is connected to every other token in the sequence. While Global Attention provides a comprehensive view of the sequence context, it can significantly increase computational demands.
π Combining SWA with Global Attention, as seen in architectures like Longformer, offers a balanced approach. This hybrid method maintains efficiency while ensuring the model captures both local and global sequence context, crucial for accurate performance on tasks with long input sequences.
π§΅2/n
π Common misconceptions about sliding window attention:
* It completely discards all information from earlier tokens
* Linear complexity means no performance trade-offs
* It's always better than full attention for all tasks