# Lucas Martín Calderón > Lucas Martín Calderón (also written Lucas Martin Calderon or Lucas Calderon) is the founder and CEO of Kash (kash.bot), the social-native prediction market: any opinion in a feed can become a market, created by anyone and traded where the conversation happens. He is an engineer and founder whose earlier work in regulated markets, AI, cryptography and trading systems is what Kash is built from. Lucas designed the market maker behind Kash himself, and has already built in each discipline a social prediction market depends on: market design, regulation, AI and cryptography. The facts below are stated the same way on the site's pages. Key facts: - Role: founder and CEO of Kash (kash.bot). - Company: Kash is the first peer-to-peer prediction market of its kind, built into social conversation. It has traded millions in volume and raised $2M from investors including Coinbase Ventures, Spartan Group and Big Brain Holdings. - Backing: Kash raised $2M from Spartan Group and Big Brain Holdings, who led the round, with Coinbase Ventures, Polaris Fund, Fabric Ventures, Kosmos Ventures, Moonrock Capital and Halo Capital. - Research: a pre-print on the Kash market maker, with UCL, is in preparation. - Negotiation: Lucas studied the craft at the Program on Negotiation at Harvard Law School, the home of Getting to Yes: a week in person, then the master class. - Speaking: invited to speak at the World Economic Forum in Davos, ETHDenver, RWA Summit and DappCon. - Recognition: named Supernova Under 30 by Nova Talent. Career, in order (earliest first): 1. Deutsche Bank: Senior Technology Analyst. 2. DiamondNXT: CISO, then CEO. 3. Pentestify: Founder. Designed its AI. 4. Crypto hedge funds: Trading systems with two of the largest. 5. Kash: Founder and CEO. What Lucas has done, by discipline: Regulation. He turns new markets into institutional infrastructure. - Lucas joined DiamondNXT as its CISO and became its CEO. He raised $2M from government and private investors, and worked with banks, FCA executives and crypto regulators to build the infrastructure for a regulated market in tokenised diamonds. The company is still active. - Diamonds, onchain: Engineered a capsule that captures each diamond’s digital fingerprint, tied it to GIA grading and put its provenance onchain, ready for fractional ownership. - Compliance: Built AML, KYC and custody to the standard banks require. Trained by FBI and US Secret Service instructors in tracing financial crime onchain. Technology. He builds where several difficult technologies must become one simple product. - Pentestify: Turned one-off smart-contract audits into continuous, AI-driven vulnerability discovery. Lucas designed its core himself: graph neural networks working with LLMs. Backed by the UK’s National Cyber Security Centre (NCSC). UCL Hatchery Startup of the Year and winner of the Merge Madrid Startup Battle. - PETs4DeFi: Pentestify is a partner in PETs4DeFi, a €3.65M Horizon Europe research programme on privacy for DeFi, run by 17 organisations across Europe. Lucas co-led the proposal and works on its cryptography. - FPGA trading engine: A trading engine for Ethereum networks, built in hardware. It runs AI models and zero-knowledge proofs on the chip. - A new market maker: Designed the automated market maker behind Kash. A new market can trade from its first moment, with no market maker to seed it. A pre-print with UCL is in preparation. Business. Traders, investors and teams follow the work. - Traders: Built trading systems with two of the largest crypto hedge funds: the first around his FPGA engine, the second for high-frequency arbitrage across Polymarket, Kalshi and Hyperliquid. - Investors: Raised $2M for DiamondNXT, won UK government backing for Pentestify, then raised $2M for Kash from Spartan Group, Big Brain Holdings, Coinbase Ventures and five more funds. - Team: People who worked with Lucas at his earlier companies have followed him to Kash. How Kash works: - Any moment in a conversation can become a market. AI writes its rules, a purpose-built market maker makes it tradable, and AI settles it from verifiable evidence. - Market design: A market maker of Lucas’s own design. Every market is live from its first trade. - Regulation: Markets that platforms, institutions and regulators can accept. - AI: The Kash Council: AI that writes each market’s rules and settles its outcome. Built with a Stanford PhD fellow. - Cryptography: Resolution settled from verifiable evidence. - Growth loop: Creators bring audiences → Audiences predict → Predictions produce fees and data → Fees and data attract the next creator. In one sentence: Kash turns attention into markets, and Lucas Martín Calderón has already built each piece it requires. Contact: book a call at https://calendly.com/lucasmartincalderon, or message Lucas on LinkedIn at https://www.linkedin.com/in/lucasmartincalderon. ## Origin: Finance was always a technology problem. Lucas started at Deutsche Bank as a Senior Technology Analyst, at the point where complex systems become financial infrastructure. It showed him how institutions adopt technology: security, regulation, operations and a commercial case all have to hold at once. That became the pattern behind everything that followed. ### The path, in order 1. Deutsche Bank: Senior Technology Analyst. 2. DiamondNXT: CISO, then CEO. 3. Pentestify: Founder. Designed its AI. 4. Crypto hedge funds: Trading systems with two of the largest. 5. Kash: Founder and CEO. ## Regulation: He turns new markets into institutional infrastructure. Permission to exist. New markets scale when the technology, the asset and the rules can be trusted together. Lucas joined DiamondNXT as its CISO and became its CEO. He raised $2M from government and private investors, and worked with banks, FCA executives and crypto regulators to build the infrastructure for a regulated market in tokenised diamonds. The company is still active. ### The evidence - **Diamonds, onchain.** Engineered a capsule that captures each diamond’s digital fingerprint, tied it to GIA grading and put its provenance onchain, ready for fractional ownership. - **Compliance.** Built AML, KYC and custody to the standard banks require. Trained by FBI and US Secret Service instructors in tracing financial crime onchain. ### Regulation in Kash A market anyone can create still has to be one that banks, institutions and regulators can trust. Lucas has already taken a new asset class through all three. - Market rules - Institutional trust - Regulatory engagement ## Technology: He builds where several difficult technologies must become one simple product. The edge. Kash combines market design, AI, cryptography, security and consumer UX in one system. ### The evidence - **Pentestify.** Turned one-off smart-contract audits into continuous, AI-driven vulnerability discovery. Lucas designed its core himself: graph neural networks working with LLMs. Backed by the UK’s National Cyber Security Centre (NCSC). UCL Hatchery Startup of the Year and winner of the Merge Madrid Startup Battle. - **PETs4DeFi.** Pentestify is a partner in PETs4DeFi, a €3.65M Horizon Europe research programme on privacy for DeFi, run by 17 organisations across Europe. Lucas co-led the proposal and works on its cryptography. - **FPGA trading engine.** A trading engine for Ethereum networks, built in hardware. It runs AI models and zero-knowledge proofs on the chip. - **A new market maker.** Designed the automated market maker behind Kash. A new market can trade from its first moment, with no market maker to seed it. A pre-print with UCL is in preparation. ### Technology in Kash Research, put to work. In Kash it becomes the market maker, the AI that creates each market and the resolution that settles it. - The AMM - The Kash Council - Resolution ## Business: Traders, investors and teams follow the work. From engine to market. The commercial record sits beside the technical one. ### The evidence - **Traders.** Built trading systems with two of the largest crypto hedge funds: the first around his FPGA engine, the second for high-frequency arbitrage across Polymarket, Kalshi and Hyperliquid. - **Investors.** Raised $2M for DiamondNXT, won UK government backing for Pentestify, then raised $2M for Kash from Spartan Group, Big Brain Holdings, Coinbase Ventures and five more funds. - **Team.** People who worked with Lucas at his earlier companies have followed him to Kash. ### Business in Kash Kash is not a research project looking for a market. Its founder has built trading systems for prediction markets, raised capital for three companies and brought his people with him. - Trading firms - Venture capital - The team ## Negotiation: Every deal here was a negotiation. Lucas studied the craft at the Program on Negotiation at Harvard Law School, the home of Getting to Yes: a week in person, then the master class. ## Kash: Three disciplines. One company. Kash is the first peer-to-peer prediction market of its kind, built into social conversation. It has traded millions in volume and raised $2M from investors including Coinbase Ventures, Spartan Group and Big Brain Holdings. Any moment in a conversation can become a market. AI writes its rules, a purpose-built market maker makes it tradable, and AI settles it from verifiable evidence. Serious financial infrastructure, compressed into a social action. ### What Kash needs, and where Lucas has done it - **Market design.** In Kash: A market maker of Lucas’s own design. Every market is live from its first trade. Where Lucas has done it: Arbitrage systems across Polymarket, Kalshi and Hyperliquid, built with one of the largest crypto hedge funds. From: Business. - **Regulation.** In Kash: Markets that platforms, institutions and regulators can accept. Where Lucas has done it: The infrastructure for a regulated market in tokenised diamonds at DiamondNXT, built with banks, FCA executives and crypto regulators. From: Regulation. - **AI.** In Kash: The Kash Council: AI that writes each market’s rules and settles its outcome. Built with a Stanford PhD fellow. Where Lucas has done it: The AI behind Pentestify: graph neural networks working with LLMs. From: Technology. - **Cryptography.** In Kash: Resolution settled from verifiable evidence. Where Lucas has done it: PETs4DeFi, a €3.65M Horizon Europe programme on privacy for DeFi, and zero-knowledge proofs accelerated in hardware. From: Technology. ### Backed by Kash raised $2M from Spartan Group and Big Brain Holdings, who led the round, with Coinbase Ventures, Polaris Fund, Fabric Ventures, Kosmos Ventures, Moonrock Capital and Halo Capital. ## The opportunity: The attention is already there. The hard part is turning it into a market fast enough. Prediction markets were built for listed events and sophisticated traders. Kash is built for everyone in the feed. ### The flywheel 1. Creators bring audiences 2. Audiences predict 3. Predictions produce fees and data 4. Fees and data attract the next creator Kash turns attention into markets. ## Frequently asked questions ### Who is Lucas Martín Calderón? Lucas Martín Calderón is the founder and CEO of Kash (kash.bot), a VC-backed company building social-native prediction markets. Before Kash he was CEO of DiamondNXT, founded the AI security company Pentestify and built trading systems with two of the largest crypto hedge funds. ### What is Kash (kash.bot)? Kash turns social conversations into prediction markets. Any moment can become a market in seconds, created by anyone, traded where the conversation is happening and settled by AI from verifiable evidence. It is the first peer-to-peer prediction market of its kind and has traded millions in volume. ### Why is Lucas the right founder to build Kash? Kash needs market design, regulation, AI and cryptography in one product, and Lucas has built in each. He designed the Kash market maker himself and built prediction-market arbitrage systems with one of the largest crypto hedge funds. At DiamondNXT he built the infrastructure for a regulated market in tokenised diamonds, and at Pentestify he designed the AI. ### What did Lucas do before Kash? In order: Lucas was a Senior Technology Analyst at Deutsche Bank. He joined DiamondNXT as CISO and became its CEO, raising $2M. He founded Pentestify, an AI security company backed by the UK’s National Cyber Security Centre (NCSC). He then built trading systems with two of the largest crypto hedge funds, and founded Kash. ### How much has Kash raised, and who backs it? Kash has raised $2M. Spartan Group and Big Brain Holdings led the round, with participation from Coinbase Ventures, Polaris Fund, Fabric Ventures, Kosmos Ventures, Moonrock Capital and Halo Capital. ### Has Lucas trained in negotiation? Yes. Lucas studied negotiation at the Program on Negotiation at Harvard Law School: a week in person, then the master class. He has raised capital for three companies, with governments, banks and funds across the table. ### Where has Lucas spoken, and what recognition has he received? Lucas has been invited to speak at the World Economic Forum in Davos, ETHDenver, RWA Summit and DappCon. He was named Supernova Under 30 by Nova Talent, and Pentestify won UCL Hatchery Startup of the Year and the Merge Madrid Startup Battle. ### How can I contact Lucas? Book a 30-minute call at calendly.com/lucasmartincalderon, or message him on LinkedIn. His email address is on the contact section of lucasmartincalderon.com. ## PETs4DeFi: Privacy-Enhancing Technologies for DeFi https://lucasmartincalderon.com/writing/pets4defi A €3.65M Horizon Europe research programme, with Pentestify as a partner, building the zero-knowledge tools that let DeFi hold privacy and compliance at once. ### A Horizon Europe research programme PETs4DeFi (Privacy-Enhancing Technologies for Compliant Decentralised Finance) is a three-year research programme funded by the European Union under Horizon Europe, with €3.65M. Seventeen organisations take part, coordinated by Aston University. Pentestify, the company Lucas founded, is one of them, and Lucas co-led the proposal. The public record, with the funding, the dates and every partner, is on [CORDIS](https://cordis.europa.eu/project/id/101308999), the European Commission's research database. ### What it sets out to build In DeFi, privacy and compliance are usually traded against each other. PETs4DeFi sets out to hold both at once: a user proves what a regulator needs to know, with a zero-knowledge proof, and reveals nothing else. The programme plans to build: - Zero-knowledge proofs for compliance, so a claim can be checked without the data behind it. - Self-sovereign identity with verifiable credentials and a zero-knowledge KYC process. - A privacy-preserving compliance oracle that a smart contract can call. - Two pilots: a decentralised exchange and a lending protocol. ### Lucas's part Lucas works on the cryptography: the zero-knowledge and identity layers the pilots are built on. ### Compliance by design The usual answer to DeFi compliance is a centralised KYC checkpoint in front of a permissioned wrapper. PETs4DeFi takes the opposite view: compliance becomes something a smart contract can *prove*, rather than a permission a custodian asserts. ## Hardware Optimisations for Crypto High-Frequency Trading and ZKPs Part I https://lucasmartincalderon.com/writing/hardware-optimisations-hft-zkps-part-i CPUs vs GPUs vs FPGAs, and why FPGA is the right substrate for low-latency MEV strategies and ZK proof acceleration. ### Introduction In the dynamic and highly competitive world of high-frequency trading (HFT), especially in the cryptocurrency market, optimizing the performance of trading algorithms is paramount. Field-Programmable Gate Arrays (FPGAs) offer significant advantages for this purpose, particularly in environments where low latency and high throughput are crucial. This article explores the technical specifics of implementing algorithms on FPGAs versus GPUs or CPUs, with a focus on spotting and optimizing FPGA implementations for MEV (Maximal Extractable Value) opportunities in crypto trading. ### Technical Considerations for FPGA, GPU, and CPU #### Parallel Processing Capabilities - **FPGAs:** Excellent at handling multiple parallel tasks due to their reconfigurable logic blocks. Ideal for algorithms that benefit from parallel execution, such as those used in MEV strategies where multiple transaction orders need to be processed simultaneously. - **GPUs:** Also strong in parallel processing, but generally designed for a higher level of data parallelism suited for graphics rendering or large-scale scientific computations. - **CPUs:** Less efficient at parallel processing compared to FPGAs or GPUs. Best suited for sequential task processing. #### Latency and Throughput Optimisation - **FPGAs:** Can be finely tuned for low-latency operations, essential in HFT where millisecond differences can impact profitability. FPGAs allow for the implementation of complex trading logic directly into hardware, minimizing the time taken for data processing and decision-making. - **GPUs:** While fast, the overhead of managing GPU kernels and memory can introduce latency that might be detrimental in HFT scenarios. - **CPUs:** Generally have higher latency and are less efficient in throughput compared to FPGAs and GPUs. #### Energy Efficiency - **FPGAs:** Consume significantly less power than GPUs and CPUs when optimized for specific tasks, which is crucial in reducing operational costs in data centers. - **GPUs and CPUs:** Typically have higher energy consumption, which can be a disadvantage in large-scale deployments. #### Reconfigurability - **FPGAs:** Offer the unique advantage of being reconfigurable, allowing traders to update their trading algorithms without hardware changes. This is particularly beneficial in the crypto space, where trading strategies and regulations can change rapidly. - **GPUs / CPUs:** Less flexible in terms of reconfiguration. Software updates are possible but replacing or upgrading hardware is often necessary for major changes. ### Spotting FPGA Implementations for Optimisation in HFT #### Algorithmic Structure Analysis - Identify algorithms within the trading system that are inherently parallelizable. MEV opportunities, such as arbitrage between different cryptocurrencies, are prime candidates. - Analyse the computational bottlenecks in current trading strategies. Any process that is latency-sensitive and involves repetitive, deterministic computations is a potential candidate for FPGA optimisation. ### Example 1: Arbitrage Strategy Implementation **Scenario:** Arbitrage in cryptocurrency involves exploiting price differences of the same asset across multiple exchanges. For instance, Bitcoin might be priced differently on Coinbase and Binance at the same moment. #### Mathematical Basis Arbitrage opportunity detection: - Suppose Bitcoin is priced at `P_C` on Coinbase and `P_B` on Binance. - Arbitrage profit potential: `ΔP = P_B − P_C`. - If `ΔP > 0`, buy on Coinbase and sell on Binance. If `ΔP < 0`, the reverse. Latency and throughput: - Latency `L` is critical for timely execution. `L` includes time to detect the price difference and execute trades on both platforms. - FPGA can reduce `L` by parallelizing price-data fetching and order-execution algorithms, effectively reducing the response time. #### FPGA Optimisation - Implement parallel processing units within the FPGA to simultaneously fetch price data from multiple exchanges. - Utilize dedicated logic blocks for real-time calculation of `ΔP` and immediate execution decision logic. - Example: an FPGA could be programmed with logic cells that immediately trigger buy/sell orders based on pre-defined `ΔP` thresholds, executing trades in microseconds. #### Proof of Concept Performance improvement: - Assume CPU-based system latency: 500 microseconds. - FPGA-implemented system latency: 100 microseconds. - In high-frequency trading, reducing latency by 400 microseconds can significantly increase the probability of executing profitable trades before the arbitrage opportunity disappears. ### Example 2: Front-Running Prevention in MEV **Scenario:** Front-running in crypto trading is where a trader executes orders on a prediction of future trades from others, based on available market information, often exacerbating MEV issues. #### Mathematical Basis Detection and response algorithm: - Use predictive analytics to assess patterns indicating a large upcoming transaction. - Calculate the optimal time and price for entering and exiting trades to minimize risk and maximize profit. #### FPGA Optimisation - Implement algorithms that analyze order-book patterns to detect signs of imminent large transactions. - Configure FPGAs to execute counter-orders instantaneously when certain conditions are met, effectively mitigating the impact of front-running by dispersing trade execution times and volumes. #### Proof of Concept Simulated trading environment: - Simulate an environment where a large order is detected. - FPGA system reacts within 50 microseconds to adjust the strategy, whereas CPU/GPU systems take about 500 microseconds. - The faster reaction time allows the FPGA-equipped trader to better position their trades, reducing potential losses due to front-running. #### Performance Metrics and Benchmarking Statistical analysis: - Collect data on the number of successful arbitrage and front-running prevention instances over a period. - Analyze the profitability and missed opportunity rate comparing FPGA-based systems against CPU/GPU-based systems. - Use statistical tools to validate the significance of performance improvements, ensuring that observed benefits are not due to random variations but are statistically significant enhancements brought by FPGA optimisations. ### Hardware Optimisations for Zero-Knowledge Proofs using FPGAs In addition to the considerations outlined previously, the deployment of FPGAs in Zero-Knowledge (ZK) proof systems offers a pertinent illustration of how FPGAs can be optimized for high-frequency trading, especially when leveraging MEV opportunities in cryptocurrency markets. Let's explore specific algorithms used in ZK proofs that can be optimized with FPGAs, and how these optimisations can enhance trading strategies. #### Algorithms Used in ZK Proofs Optimized for FPGAs **Multi-Scalar Multiplication (MSM)** - *Description:* MSM is a core computational element in many cryptographic protocols, including those used in ZK proofs. It involves the computation of multiple scalar multiplications and then summing them up. - *FPGA optimisation:* FPGAs can accelerate MSM by parallelizing multiple scalar multiplications and efficiently managing data flow between operations. This results in faster computation times which is crucial for real-time trading systems where quick decision-making based on ZK proofs can provide a competitive edge. **Number Theoretic Transform (NTT)** - *Description:* NTT is used in polynomial arithmetic operations underpinning ZK proofs, similar to the Fast Fourier Transform (FFT) but over finite fields. - *FPGA optimisation:* Implementing NTT on FPGAs allows for high-throughput and low-latency computation of polynomial operations. This is essential for ZK applications where the polynomial operations must be computed quickly to keep up with the demands of HFT. **Poseidon Hash Function** - *Description:* Poseidon is a hash function optimized for ZK circuits, offering efficient performance in environments where proof generation and verification are required. - *FPGA optimisation:* By designing custom FPGA circuits specifically for the Poseidon hash function, the hash computations can be massively sped up, reducing the overall time required for generating and verifying ZK proofs in trading algorithms. #### Examples and Mathematical Proof of FPGA Benefits in HFT **Example 1: Optimizing arbitrage strategies using MSM** - *Mathematical basis:* Arbitrage involves identifying price discrepancies across markets and quickly executing trades to capitalize on these differences. Using MSM, the FPGA can rapidly calculate potential profits from different trade combinations across multiple markets. - *FPGA implementation:* An FPGA can be programmed to perform MSM operations to evaluate multiple arbitrage opportunities concurrently, thus minimizing the time from signal to trade execution. The parallel processing capabilities of FPGAs allow for simultaneous calculations of multiple trade outcomes, significantly outpacing CPU/GPU-based systems. **Example 2: Enhancing front-running defence mechanisms using Poseidon hash** - *Mathematical basis:* In crypto trading, front-running is a major concern where traders anticipate other trades and act on this information unfairly. - *FPGA implementation:* FPGAs can implement the Poseidon hash function to create a secure and tamper-evident record of incoming trades. By hashing trade details and comparing them in real-time, FPGAs can help ensure that all trades are executed in the correct order, thereby mitigating potential front-running scenarios. #### Performance Metrics and Benchmarking - **Latency reduction:** Implementations on FPGAs can reduce the latency of cryptographic computations by an order of magnitude compared to CPUs and GPUs. - **Throughput increase:** FPGAs' ability to handle multiple operations in parallel can lead to a significant increase in throughput, essential for processing high volumes of trades or cryptographic proofs in HFT. **Performance benchmarking** - Compare the current performance metrics of algorithms running on CPUs or GPUs with their theoretical performance on FPGAs. - Implement pilot projects to test the feasibility of shifting critical parts of the trading algorithm to FPGAs. #### Regulatory and Compliance Considerations - Ensure that any reconfiguration of trading algorithms on FPGAs complies with financial regulations and security standards. - Maintain flexibility in the FPGA design to quickly adapt to regulatory changes. #### Cost-Effectiveness Analysis - Evaluate the cost implications of deploying FPGAs, including initial investment, maintenance, and potential ROI from increased trading efficiencies. - Consider the scalability of FPGA implementations as trading volumes and algorithm complexity increase. ### Conclusion The implementation of FPGAs in high-frequency trading, particularly within the field of cryptocurrency markets and applications involving Zero-Knowledge Proofs (ZKPs) for enhanced privacy, reflects a significant performance and efficiency advantage over traditional CPU/GPU setups. By examining the intrinsic capabilities and outcomes of FPGA-based systems, we can delineate a comprehensive understanding of their superior performance metrics and strategic value in modern trading environments. FPGAs, with their exceptional parallel processing abilities, are fundamentally equipped to handle the simultaneous execution of multiple operations — a capability that is crucial for the fast-paced decision-making required in HFT. This is particularly pertinent when trading systems need to execute complex cryptographic algorithms such as Multi-Scalar Multiplication (MSM), Number Theoretic Transform (NTT), and Poseidon hash functions that are central to Zero-Knowledge Proof applications. The direct hardware execution ability of FPGAs allows these algorithms to run faster than on CPUs and GPUs, providing a critical edge in reducing latency, which is paramount in exploiting MEV opportunities where milliseconds can dramatically impact trading outcomes. Moreover, FPGAs offer superior energy efficiency and the flexibility to be reconfigured for different tasks without needing physical hardware replacements. This adaptability is invaluable in the crypto trading context, where market conditions and regulatory requirements can change swiftly, necessitating agile adjustments in trading strategies and computational approaches. In contrast, while GPUs provide robust parallel processing capabilities, they are generally optimized for data-heavy computations found in graphics rendering or large-scale scientific analyses rather than for the ultra-low latency required in financial trading. GPUs do excel in environments where the sheer volume of data or breadth of computation is extensive, yet they lag in the immediacy of execution provided by FPGAs. CPUs, although highly versatile and capable of handling a broad range of tasks, fall behind in both the specialized high-speed processing of FPGAs and the high-throughput data handling of GPUs. The sequential nature of CPU processing results in higher latencies compared to FPGAs, which can be a significant disadvantage in scenarios where trading opportunities may vanish in the blink of an eye. Furthermore, the use of FPGAs in the implementation of Zero-Knowledge Proofs offers enhanced privacy and security in cryptocurrency transactions, ensuring that trading strategies and the particulars of transactions remain confidential while still providing proof of their validity. This aspect of FPGAs is especially crucial in an era where financial transparency needs to meet stringent security and privacy standards. To conclude, for high-frequency trading in cryptocurrency and applications leveraging Zero-Knowledge Proofs, FPGAs are demonstrably superior to GPUs and CPUs due to their lower latency, higher throughput, and greater flexibility. These characteristics not only result in faster and more secure trading operations but also enable traders to maintain a competitive advantage in the volatile and rapidly evolving crypto market. The ability to swiftly adapt to market conditions, execute trades with minimal delay, and uphold stringent security protocols through ZKPs makes FPGAs the preferred technology in cutting-edge financial trading platforms. ## Achieving superior blockchain security with SGX and ZK proofs https://lucasmartincalderon.com/writing/sgx-and-zk-proofs Fatal SGX vulnerabilities and how multi-prover systems, combining SGX with ZK proofs and FHE, harden rollups. ### Introduction The realm of blockchain technology and cryptographic security continually evolves, with innovations such as ZK-Rollups, circuits, and SNARKs at the forefront of this transformation. However, the complexity and relative immaturity of these technologies pose risks, including potential bugs and security vulnerabilities. A strategic approach to mitigating these risks involves the adoption of a multi-prover system. This system leverages a variety of proof types (like validity proofs and fraud proofs), different proving systems (e.g., SNARK and STARK), and distinct implementations crafted by diverse teams. Such a multi-layered approach significantly enhances the security and robustness of blockchain networks. This article unfolds in five critical parts. First, we delve into the essence of the multi-prover strategy, exploring its components beyond just the proving system. Second, we illuminate the concept and mechanics of SGX (Software Guard Extensions) as a form of validity proof and examine its role as a reliable addition to cryptographic and economic frameworks. Then we elucidate how the multi-prover system functions within nodes and smart contracts, particularly focusing on its application in rollups. We dig deeper into some common and critical vulnerabilities of SGX. Finally, we compare how ZK and FHE can complement this technology for it to be applicable widely in the blockchain space. ### Why Multi-Proof Matters in Blockchain Security #### Challenges in Current Technologies Blockchain technologies, especially those involving complex constructs like ZK-EVM circuits, are inherently intricate and laden with thousands of code lines. This complexity inevitably leads to a longer path towards achieving a bug-free environment. The risks are manifold — spanning across the proving systems, circuit compilers, and the ZK-EVM code itself. Moreover, the cryptographic primitives underpinning ZK-Rollups, predominantly SNARKs, are relatively new. Their novelty brings an inherent uncertainty in terms of undiscovered vulnerabilities within the proving systems themselves. #### The Multi-Prover Solution In response to these challenges, the multi-prover approach offers a resilient safety net. This strategy involves generating several types of proofs for a single block. Consequently, even if one proof type is compromised, the presence of others obstructs the exploitation of the same vulnerability. In scenarios where a particular proof type fails to validate a block, the multi-prover system's design could lead to a temporary halt in the chain's operations, contingent on the acceptance criteria set for validating a block. This additional layer of requiring diverse proof types significantly elevates the overall security. > *Disclaimer:* Henceforth, our reference to "multi-prover" encapsulates the diversity in proof types. #### A Conceptual Analogy To better grasp the concept of a multi-prover system, we can draw a parallel with the client diversity in Ethereum's network. This diversity allows Ethereum to withstand and recover from partial network failures. As Vitalik Buterin articulates in his discourse, Ethereum's approach to using multiple clients is a form of decentralization that brings both technical and social benefits. These benefits range from architectural diversity to the prevention of power centralization within the network's operational team. Similarly, the multi-prover philosophy in Rollups champions both technical and social advantages. Technically, it encompasses varied proving systems, architectural designs, and implementations. Socially, it promotes a distribution of power, ensuring that no single entity holds disproportionate influence within the blockchain infrastructure. ### Diversified Construction of Multi-Prover Systems The architecture of a multi-prover system is inherently diverse, incorporating various elements that collectively fortify the blockchain against a myriad of vulnerabilities. #### Variety in Proof Types Multi-prover systems don't just hinge on a single type of proof. They amalgamate different kinds, such as: - **Fraud proofs:** Commonly utilized in optimistic rollups, these proofs operate on fundamentally different principles compared to validity proofs, greatly reducing the likelihood of correlated vulnerabilities. - **Validity proofs:** Typically seen in zk-rollups, these proofs are based on different computational assumptions and methodologies. - **Innovative proving systems like SGX:** As a less conventional but emerging option, SGX (Software Guard Extensions) provides an additional layer of security. We'll explore SGX in greater detail later in this article. #### Multiple Proving Systems The multi-prover framework isn't just about using different types of proofs; it's also about employing varied proving systems. For instance, in the context of zk-rollups, both SNARK and STARK backends can be utilized. The dual-use of these systems not only introduces redundancy but also mitigates the risk of systemic failures in any single proving system. #### Diverse Implementations by Varied Teams A robust multi-prover approach involves different teams working on separate implementations. This diversity significantly reduces the risk of a universal bug affecting the entire network, as the likelihood of different teams making identical errors in their code is minimal. #### Addressing the Risks of Broken Proofs In a multi-prover ecosystem, the possibility exists that different proof types may yield conflicting results for the same block. This situation necessitates an understanding of two key properties of proofs: completeness and soundness. - **Completeness issues:** If a proof for a valid block cannot be generated, it implies a breakdown in completeness. In such scenarios, depending on the blockchain's design (e.g., the number of required proofs), the entire chain might temporarily halt. - **Soundness concerns:** This arises when multiple proofs for a valid block result in different block hashes. Ideally, only the proof for the correct blockhash should be possible. If the same vulnerability impacts multiple proof types, leading to the submission of incorrect blockhashes, the integrity of the multi-prover system could be compromised. To address these risks, especially when using two types of proofs, a multi-sig governance mechanism can serve as an emergency resolution method. This entity would determine the correct blockhash and take necessary actions (like updating or excluding the faulty proof type). The decision-making in scenarios involving more than two proof types might hinge on a majority consensus regarding the validity of the proofs, followed by corrective measures against the erring proofs. ### Understanding SGX and Its Role in Blockchain #### What is SGX? SGX, or Software Guard Extensions, represents a significant stride in the domain of secure computing. Developed by Intel, SGX is a set of security-related instruction codes that enable the creation of protected memory spaces, known as enclaves. #### How SGX Works At its core, SGX allows for the establishment of enclaves, which act as fortified, isolated compartments within a processor. These enclaves are designed to be a secure space where code and data can be kept protected from external threats, including those originating from the system's own operating system. In blockchain applications, SGX can be a game-changer, particularly for private smart contracts. For instance, running an oracle within an SGX enclave can enhance privacy and security, providing proof of data integrity without revealing the data itself. > Secure remote computation: a user relies on a remote computer, owned by an untrusted party, to perform some computation on her data. The user has some assurance of the computation's integrity and confidentiality. #### SGX's Structure and Key Components - **Trusted Computing Base (TCB):** This encompasses the hardware, firmware, and software essential for creating a secure computing environment. - **Hardware secrets:** Such as the Root Provisioning Key (RPK) and Root Seal Key (RSK), which are integral to the hardware's secure operations. - **Attestation mechanisms:** These are crucial for verifying the integrity and security of the code running within the enclaves. SGX offers two attestation forms: local and remote. Local attestation is used within the same trusted computing base, whereas remote attestation allows external entities to verify the enclave's integrity. > Software attestation proves to a remote computer that it is communicating with a specific secure container hosted by a trusted platform. The proof is an attestation signature produced by the platform's secret attestation key. The signature covers the container's initial state, a challenge nonce produced by the remote computer, and a message produced by the container. #### Challenges and Limitations of SGX Despite its robust design, SGX isn't without its challenges. Trusting Intel's hardware and the security of the SGX technology itself can be seen as a potential risk. Furthermore, the complexity and novelty of SGX mean that its reliability in various attack scenarios is still an evolving area. Security in SGX also doesn't exist in isolation and often needs to be supplemented with other cryptographic methods or economic incentives for a well-rounded defense strategy. ### SGX Doubts, Constraints, and Weak Points #### 1. Trust in the Technology and Provider Utilizing SGX necessitates a degree of trust in Intel, the technology's creator. This trust extends to the belief that the SGX technology is robust against various attack vectors and that Intel will be responsive in patching new vulnerabilities as they emerge. However, skepticism remains, especially given the history of delay in addressing known SGX attacks. Furthermore, Intel's decision to deprecate SGX in consumer CPUs in 2021 raises questions about its long-term viability and support. #### 2. The Newness of the Technology SGX, being relatively new, is still under scrutiny regarding its overall reliability. The lack of extensive real-world testing and understanding of potential attack vectors means that the full spectrum of its security capabilities is yet to be established. #### 3. Security Beyond the Hardware While SGX provides a secure hardware environment, it isn't a standalone solution for all security needs. To build a comprehensive security model, SGX should be integrated with other cryptographic methods such as Multi-Party Computation (MPC), Zero-Knowledge Proofs (ZKP), Fully Homomorphic Encryption (FHE), and Oblivious RAM (ORAM). Balancing SGX's technical strengths with economic incentives and other security mechanisms can create a more resilient overall system. #### 4. High-Level CPU Diagram Static Random Access Memory (SRAM) cells, generally known as registers, are significantly faster than DRAM cells, but also a lot more expensive. An instruction performs a simple computation on its inputs and stores the result in an output location. The processor's registers make up an execution context that provides the inputs and stores the outputs for most instructions. For example, `ADD RDX, RAX, RBX` performs an integer addition, where the inputs are the registers `RAX` and `RBX`, and the result is stored in the output register `RDX`. The instruction pointer (`RIP`) stores the memory address of the next instruction to be executed by the processor, and the stack pointer (`RSP`) stores the memory address of the topmost element in the call stack. Under normal circumstances, the processor repeatedly reads an instruction from the memory address stored in `RIP`, executes the instruction, and updates `RIP` to point to the following instruction. Unlike many RISC architectures, the Intel architecture uses a variable-size instruction encoding, so the size of an instruction is not known until the instruction has been read from memory. While executing an instruction, the processor may encounter a fault, which is a situation where the instruction's preconditions are not met. When a fault occurs, the instruction does not store a result in the output location; instead, the instruction's result is considered to be the fault that occurred. The processor first looks up the address of the code that will handle the fault, based on the fault's nature, and sets up the execution environment in preparation to execute the fault handler. Each device attached to the bus decodes the operation codes and addresses of all the messages sent on the bus and ignores the messages that do not require its involvement. For example, when the processor wishes to read a memory location, it sends a message with the operation code `READ-REQUEST` and the bus address corresponding to the desired memory location. The memory sees the message on the bus and performs the `READ` operation. At a later time, the memory responds by sending a message with the operation code `READ-RESPONSE`, the same address as the request, and the data value set to the result of the `READ` operation. The computer communicates with the outside world via I/O devices, such as keyboards, displays, and network cards, which are connected to the system bus. ### Existing Blockchain Implementations with SGX #### 1. Development Tools and Frameworks To facilitate the integration of SGX into blockchain applications, several SDKs and libraries are available, including Intel's SGX SDK, Open Enclave, Rust SGX, and Teaclave. For existing applications that need to run in isolated environments without significant code modifications, library operating systems (libOSes) like Gramine, Occlum, and EGo have been developed. These provide a Linux-like abstraction layer, helping to adapt applications to secure enclave environments. #### 2. Pioneering Efforts in Blockchain Organizations like Flashbots and Nethermind have been at the forefront of exploring SGX within the blockchain space. One notable application is running Ethereum's Geth client inside an SGX enclave. Though feasible, this approach presents challenges, including high memory requirements, long startup times, and potential information leakage risks. How memory is handled with SGX: the virtual memory abstraction gives each process its own virtual address space. The operating system multiplexes the computer's DRAM between the processes, while application developers build software as if it owns the entire computer's memory. #### 3. Block Building and Transaction Privacy within SGX Another critical application of SGX in blockchain is in the area of private transactions and decentralized block building. By running the block-building process within SGX enclaves, the contents of user transactions can be kept private, and the block construction can be done in a verifiable manner. However, challenges such as managing the large state size of blockchain databases and the additional performance overheads remain topics of active research and development. #### Applying SGX to Rollups SGX's application to rollups brings promising possibilities, particularly in verifying the correctness of block execution. In rollups, the verification process can be rendered stateless: the program inside the SGX enclave receives only the necessary data (like the state root, transaction list, and block parameters) as input. It then verifies these inputs against the expected output, ensuring the integrity of the block execution. This method aligns well with the principles of zero-knowledge proofs, where direct access to the state isn't possible. The SGX enclave thus serves as a trusted component that can attest to the correctness of a block's execution, adding another layer of security and integrity to the rollup process. #### Multi-Prover in a Rollup Setting In the context of rollups, implementing a multi-prover system requires the participation of nodes dedicated to proof generation. These nodes gather necessary data such as transactions, state accesses, and Merkle proofs. The generation of zk-based proofs might be resource-intensive and time-consuming, whereas SGX-based proofs can be quicker and less resource-demanding. Once generated, these proofs are submitted to the rollup smart contract collectively, ensuring that all required proofs are available for verification. The contract then checks each proof for correctness. In the case of zk proofs, this involves running a verifier algorithm; for SGX proofs, it might be as simple as verifying an ECDSA signature. The final step is to ensure that all proofs agree on the same blockhash, confirming the block's validity and marking it as proven on the chain. ### Strategic Integration of SGX with Economic Incentives #### 1. SGX and Economic Incentives: A Balanced Approach When considering the security model of blockchain systems, a nuanced approach that combines the technical assurances of SGX with the strategic application of economic incentives is vital. SGX, with its hardware-based encryption and isolated execution environments, offers a robust defense against many attack vectors. However, its effectiveness can be further enhanced when used in conjunction with well-designed economic incentives. #### 2. Complementing SGX with Economics The integration of SGX with economic models needs to consider various scenarios: - **High-risk situations:** In instances where economic models face extreme stress or breakdown (e.g., market crashes or systemic financial failures), SGX's technical security can provide a stable defense line, independent of economic fluctuations. - **Prevention of exploits:** SGX alone, while formidable, can still be susceptible to sophisticated attacks. Therefore, pairing SGX with economic deterrents (like high costs for attempting security breaches) can enhance overall system resilience. #### SGX in Blockchain: Beyond the Ideal While SGX presents an impressive array of features for enhancing blockchain security, it's crucial to acknowledge that it isn't a panacea. The complexity and evolving nature of SGX mean that it should be part of a broader strategy incorporating other security measures and techniques. For instance, combining SGX with different cryptographic primitives and economic models can help create a more well-rounded and formidable security framework. ### Understanding Intel SGX Vulnerabilities in Depth #### Understanding SGX and Its Operational Model Before diving into the vulnerabilities, let's understand the basic functioning of SGX. SGX allows applications to create protected areas in memory, called enclaves, which are designed to be resilient to attacks from both the operating system and the hardware. The cornerstone of SGX is its promise that code and data loaded in the enclave are protected and cannot be seen or modified from outside the enclave. #### 1. Exploiting Side Channels: A Pathway to Breaching SGX Side-channel attacks have emerged as a potent threat to SGX, exploiting indirect paths to glean sensitive information. These attacks typically observe variations in physical parameters like execution time or power consumption to infer data or cryptographic keys. **a. Cache attacks** Cache attacks like Prime+Probe and Flush+Reload target the processor's cache. By monitoring cache access patterns, an attacker can deduce the data being processed inside the enclave, thus compromising the confidentiality guaranteed by SGX. A malicious OS can partition a cache between the software running inside an enclave and its own malicious code. Both the OS and the enclave software have cache sets dedicated to them. When allocating DRAM to itself and to the enclave software, the malicious OS is careful to only use DRAM regions that map to the appropriate cache sets. On a system with an Intel CPU, the OS can partition the L2 cache by manipulating the page tables in a way that is completely oblivious to the enclave's software. **b. Branch prediction and speculative execution attacks** These attacks exploit the CPU's branch prediction and speculative execution features to access protected memory areas. Notable examples include Spectre and Meltdown, which have also been adapted to target SGX enclaves. **c. Page fault attacks** By inducing and observing page faults, attackers can figure out the access patterns inside the enclave, thereby inferring the data being processed. #### 2. Specific Vulnerabilities in SGX: xAPIC and MMIO The xAPIC and MMIO vulnerabilities, as exposed in the Secret Network incident, are particularly concerning. **a. xAPIC vulnerability** This vulnerability arises from a flaw in the Advanced Programmable Interrupt Controller (xAPIC) that allows an attacker to infer the data being accessed inside the enclave. By manipulating and observing the interrupt handling mechanisms, sensitive data like the consensus seed in the Secret Network can be extracted. **b. MMIO vulnerability** Memory-Mapped I/O (MMIO) attacks exploit the SGX design's handling of certain memory-mapped I/O regions. Attackers can potentially gain unauthorized access to enclave memory, leading to data leakage. #### 3. Real-World Impact and Mitigation Efforts The real-world implications of these vulnerabilities are far-reaching. The Secret Network's compromise and the potential extraction of AACS2 keys in PowerDVD are testaments to the threats posed by these SGX vulnerabilities. Mitigating these vulnerabilities often involves firmware and microcode updates, which can be challenging to deploy due to their reliance on BIOS updates, leading to a slow and cumbersome patching process. #### 4. The Challenge of Patching SGX Patching SGX vulnerabilities is not straightforward. Each update must be carefully tested to ensure it doesn't inadvertently introduce new vulnerabilities or impact the performance or functionality of the system. The delay in deploying these updates can leave systems vulnerable for extended periods. #### 5. The Future of SGX Security The ongoing discovery of SGX vulnerabilities necessitates a re-evaluation of the trust placed in enclave-based security models. While Intel and other stakeholders have been actively addressing these vulnerabilities, the evolving nature of side-channel attacks means that a single solution is unlikely to be sufficient. ### Enhancing Intel SGX Security with Zero-Knowledge Proofs and Homomorphic Encryption #### Zero-Knowledge Proofs (ZKPs): Addressing SGX Shortcomings ZKPs, a cryptographic method that enables one party to prove to another that a statement is true without revealing any information beyond the validity of the statement itself, can complement SGX in several ways: **1. Enhancing privacy against side-channel attacks** - *Mitigation strategy:* ZKPs can verify the correctness of a computation (like a smart contract execution) without revealing the input or internal state. This method counters specific side-channel attacks that target the data or the state of computations within SGX. - *Use-case example:* In blockchain, a ZKP could validate a transaction's correctness processed within an SGX enclave without exposing the transaction's details, thus maintaining transaction confidentiality despite SGX vulnerabilities. **2. Building trust despite vulnerable environments** - *Trustless verification:* ZKPs enable external validation of data processing in SGX enclaves, building trust even if the enclave itself might be compromised. - *Blockchain integration:* For blockchain networks, ZKPs can ensure the integrity and correctness of off-chain computations done within SGX enclaves, crucial for maintaining consensus and trust. #### Fully Homomorphic Encryption (FHE): A Complementary Shield FHE allows computations to be performed on encrypted data, and the results of these computations remain encrypted. FHE can address some of SGX's vulnerabilities: **1. Securing data in use** - *Protection mechanism:* Even if attackers bypass SGX protections, the data, if encrypted using FHE, remains secure as they cannot decrypt it without the corresponding keys. - *Blockchain application:* Storing encrypted blockchain states or smart contracts and allowing computations (like transaction processing) in their encrypted form enhances security and privacy. **2. Extended security boundaries** - *Data security outside enclaves:* FHE keeps data encrypted during processing outside the SGX enclave, mitigating risks related to data exposure in untrusted parts of the system. - *Blockchain scenarios:* Blockchain nodes leveraging SGX can perform certain computations on encrypted data (e.g., transaction validation) without decrypting it, reducing the attack surface. #### Practical Integration in Blockchain and Cryptography Integrating ZKPs and FHE with SGX in blockchain systems must consider the complexity and performance overheads. Implementing such systems requires a deep understanding of cryptographic primitives, SGX architecture, and blockchain protocols. **Implementing ZKPs with SGX** - *Designing ZKP protocols:* Choose ZKP types (e.g., SNARKs, STARKs) based on the trade-off between setup requirements, proof size, and computational overhead. - *Integration with SGX:* Develop SGX enclaves to generate or verify ZKPs. Ensure that the enclave's code is optimized to mitigate known side-channel attacks during ZKP computation. **Utilizing FHE alongside SGX** - *Selecting FHE schemes:* Pick suitable FHE schemes that balance between encryption strength and computational efficiency. - *SGX–FHE workflow:* Design workflows where data is encrypted via FHE outside SGX, processed within the enclave, and results are sent out still encrypted. ### Future Directions and Emerging Trends #### 1. Advancements in Technology and Security The blockchain landscape is continually evolving, with new technologies and security challenges emerging regularly. SGX, as part of this landscape, will also evolve, addressing current limitations and adapting to new threats. #### 2. Holistic Security Strategies Future blockchain implementations will likely adopt more holistic security strategies, integrating SGX with other advanced cryptographic methods and adapting to changing economic and technical environments. This approach ensures that blockchain systems remain resilient against a broad spectrum of threats, both known and unforeseen. ### Conclusion This article dug deep into the intricate world of multi-prover systems in blockchain, highlighting their significance, operational mechanisms, and the role of SGX within this framework. The multi-prover approach, by leveraging a diversity of proofs, proving systems, and implementations, significantly enhances the resilience and security of blockchain networks. SGX, with its ability to create secure and isolated execution environments, adds a valuable dimension to this approach, particularly in the context of private smart contracts and rollup verifications. However, the journey towards achieving a foolproof blockchain security model is ongoing. The continuous evolution of threats and technologies necessitates an adaptable and multi-faceted security strategy, where innovations like SGX are integrated thoughtfully with other cryptographic techniques and economic models. As blockchain technology matures and faces new challenges, the integration of these diverse yet complementary elements will be crucial in building robust, secure, and trustworthy systems. In conclusion, while the multi-prover strategy and tools like SGX significantly fortify blockchain systems, the search for impenetrable security continues. ## Verkle Trees: Everything You Need To Know https://lucasmartincalderon.com/writing/verkle-trees How Verkle trees collapse Merkle proof sizes by ~7×, and where they sit in Vitalik's Ethereum end game. *Study notes. This explainer follows Vitalik Buterin’s [Verkle trees](https://vitalik.eth.limo/general/2021/06/18/verkle.html) (2021).* ### Introduction As Ethereum continues to scale and evolve, Verkle trees emerge as a vital component. Like Merkle trees, Verkle trees facilitate the storage of vast data, allowing the generation of succinct proofs for any subset of that data. The distinguishing feature of Verkle trees is their ability to produce significantly smaller proof sizes. For instance, a traditional binary Merkle tree proof for a billion data pieces would be approximately 1 kilobyte. In contrast, a Verkle tree proof for the same data would be under 150 bytes. This drastic reduction in proof size paves the way for the practicality of stateless clients. ### Origins and Significance The concept of Verkle trees was first presented by John Kuszmaul in a 2018 paper. Although relatively new, their potential impact on cryptographic constructs is undeniable. This article delves into the essence of Verkle trees and the cryptographic nuances underpinning them. While Verkle trees rely on more intricate cryptography, their complexity is arguably less daunting than some advanced cryptographic elements in modern ZK SNARK systems. ### Tree Structure: Merkle Patricia vs. Verkle Trees The architecture of Verkle trees bears a resemblance to Ethereum's current Merkle Patricia trees. Each node within a tree can be: 1. Empty 2. A leaf node containing a unique key and corresponding value 3. An intermediate node with a predetermined number of child nodes (denoted as the "width" of the tree) The value of an intermediate node is derived from the hashed values of its child nodes. The position of a value within the tree is dictated by its key. The primary distinction between Verkle trees and Merkle Patricia trees lies in their width. While Patricia trees achieve optimal efficiency at a width of 2, Verkle trees yield shorter proofs with increasing width. However, exceedingly high widths can hinder the speed of proof creation. Proposed Verkle trees for Ethereum possess a width of 256, but there's a growing inclination to amplify this to 1024. ### Commitments and Proofs In Merkle trees, proof of a value necessitates the inclusion of all sister nodes. The reason being, to compute a node's value, the entire set of its sibling nodes is required. This continues recursively up to the root node. Verkle trees, however, circumvent the need for sister nodes by just supplying the path, augmented with minimal proof. A pivotal distinction in Verkle trees is the use of vector commitments instead of standard hashes for node computations. Vector commitments enable the creation of short proofs affirming that a value is part of a committed list. In practice, even more potent than vector commitments are polynomial commitments, which allow hashing of a polynomial and subsequent proof generation for any evaluation of the hashed polynomial. ### Merging the Proofs Verkle trees exploit the properties of polynomial commitments to generate a single, constant-sized proof, capable of substantiating all parent-child links for infinite keys. This is accomplished via a scheme that implements multiproofs through random evaluation. The specifics of this proof generation, while intricate, can be elucidated further in detailed technical articles. The chief computational burden in proof generation involves formulating a polynomial of a certain form, with the remainder of the proofing process involving polynomial commitment validation. ### Key Characteristics and Implications Proofs using this architecture possess several notable properties: 1. Proof sizes remain consistent regardless of the number of evaluations. 2. Values can be inferred from other elements in the Verkle proof. 3. Only the leaves (keys and values) being proven and the commitments along their path to the root are necessary. Given a width-256 tree and *n* nodes, a proof would typically require the keys and values being validated, complemented by an average of three commitments for every value spanning from that value to the root. ## Zero-Knowledge Proofs: Full Guide, Part IV https://lucasmartincalderon.com/writing/zk-proofs-part-iv From Zero to Knowledge: modular arithmetic, the engine room behind ZKP soundness and efficiency. We've all been there, scratching our heads, trying to make sense of numbers that seem to grow out of control in the computation of complex algorithms. When it comes to Zero-Knowledge Proofs (ZKPs), a foundational concept in blockchain security and cryptography, the need for managing large numbers is paramount. Enter the fascinating world of modular arithmetic. In this article, we'll dive into the workings of modular arithmetic, illustrate its applications in ZKPs, and explore how it helps simplify computations without losing the essential characteristics required for secure transactions. ### Introduction to Modular Arithmetic Modular arithmetic is often described as "clock arithmetic" because it operates in a cyclical manner, much like the hands of a clock. It's a powerful mathematical tool used extensively in cryptography, computer science, and, of course, ZKPs. ### The Basic Concept Imagine dividing two integers, A and B, in the standard way: `A ÷ B = Q + R` Here, *Q* is the quotient, and *R* is the remainder. In modular arithmetic, we're interested in the remainder. The expression `A mod B` yields the remainder *R*, so: `A mod B = R` For example, `10 mod 3 = 1`. #### Range of Remainders An intriguing aspect of modular arithmetic is that for any given modulus *n*, the remainder can range from 0 to *n − 1*. Let's illustrate this with an example using modulus 7. Here's a set of integers: `[1, 5, 10, 15, 22]`. When we perform `mod 7` on each of these numbers, the resulting values will fall within the range of 0 to 6: `[1 mod 7, 5 mod 7, 10 mod 7, 15 mod 7, 22 mod 7] = [1, 5, 3, 1, 1]` ### Congruence: A Closer Look Congruence is a vital concept in modular arithmetic, represented by the ≡ symbol. Two integers, *a* and *b*, are said to be congruent `mod n` if their remainders when divided by *n* are the same. **Example 1** `25 ≡ 5 (mod 10)` Because both 25 and 5 leave a remainder of 5 when divided by 10. **Example 2** `81 ≡ 9 (mod 12)` Because both 81 and 9 leave a remainder of 9 when divided by 12. Both 37 and 17, when divided by 10, leave a remainder of 7, so they are congruent `mod 10`. ### Performing Arithmetic Operations with Modulus Modular arithmetic isn't just about remainders; it's a full-fledged system allowing addition, subtraction, multiplication, and even a form of division. #### Addition In modular addition, you simply add two numbers and then take the remainder when dividing by the modulus. - `4 + 7 ≡ 1 (mod 5)` - `9 + 14 ≡ 8 (mod 15)` #### Subtraction Subtraction works similarly to addition. If the result is negative, you continue adding the modulus until you get a non-negative answer. - `6 − 10 ≡ 0 (mod 4)` - `17 − 22 ≡ 4 (mod 9)` #### Multiplication Multiplication is just as straightforward. Multiply the numbers and then take the remainder when dividing by the modulus. - `4 × 5 ≡ 6 (mod 7)` - `9 × 14 ≡ 12 (mod 19)` #### Division: Modular Inverses Division isn't directly defined in modular arithmetic. Instead, we have the concept of modular inverses. The modular inverse of *A* `(mod C)` is `A⁻¹`, such that: `A × A⁻¹ ≡ 1 (mod C)` To "divide" a number *X* by *A* in modular arithmetic, we multiply *X* by the multiplicative inverse of *A*: `X / A (mod C) = X × A⁻¹ (mod C)` If we want to divide 10 by 3 `(mod 7)`, we first find the modular inverse of 3 `(mod 7)`, which is 5. Then we multiply 10 by 5: `10 × 5 ≡ 1 (mod 7)` ### Why Modular Arithmetic is Essential in ZKPs Now that we've got the basics down, let's examine why modular arithmetic is so crucial in ZKPs. #### 1. Handling Large Numbers Modular arithmetic offers a finite set of numbers to work with. This avoids overflow issues and ensures that computations with large numbers remain manageable. *Example:* When working with 1024-bit numbers in cryptography, using a modulus keeps the numbers within a manageable range, reducing computational overhead. #### 2. Homomorphic Properties The ability to perform operations on encrypted values without decryption is vital in ZKPs. Modular arithmetic's homomorphic properties enable the proof generation without revealing the underlying values. *Example:* In a voting system, homomorphic encryption can be used to add encrypted votes together, and the result can be decrypted to reveal the final tally without exposing individual votes. #### 3. Computational Efficiency As all computations are within a fixed range, modular arithmetic is typically faster and more resource-efficient. This is especially beneficial in blockchain systems and embedded devices. *Example:* In blockchain systems, fast modular computations ensure that transactions are processed quickly, even on resource-constrained devices. ### Conclusion Modular arithmetic is more than a mathematical curiosity; it's a powerful tool that plays a pivotal role in modern cryptography and blockchain technologies. Its elegance in dealing with numbers, its rich set of operations, and its vital role in Zero-Knowledge Proofs make it an indispensable part of our digital world. For those looking to delve deeper into modular math, the Euclidean algorithm for finding modular inverses and advanced cryptographic applications are exciting areas to explore. With a solid understanding of modular arithmetic, the world of cryptography and secure computing opens up with new possibilities and challenges. ## Zero-Knowledge Proofs: Full Guide, Part III https://lucasmartincalderon.com/writing/zk-proofs-part-iii From Zero to Knowledge: proof systems, NP, IP, PCP, IOP and how zk-SNARKs / zk-STARKs descend from them. ### Introduction Zero-Knowledge Proofs (ZKPs) have emerged as a crucial building block in the world of cryptography, particularly in the blockchain realm. But what exactly are they, and why do they matter? In simple terms, a Zero-Knowledge Proof is a method by which one party can prove to another that they know a specific piece of information without revealing what that information is. Sounds intriguing, doesn't it? Let's embark on a journey to understand the fundamentals of Zero-Knowledge Proofs and explore how they are shaping the world of secure communication. ### The Foundation of Proofs Before diving into ZKPs, we need to understand what a proof system is. In computer science, a proof system consists of a formalized process to demonstrate the validity of a statement. Here's a breakdown of the major components: #### 1. Formal Language This is the syntax and symbols used to write formulas and make assertions. It's like the grammar rules of proofs. #### 2. Axioms Think of these as the fundamental truths or starting points for constructing proofs. #### 3. Inference Rules These are the logic principles that guide how one statement can lead to another. #### 4. Proof Derivation Starting from axioms, we use inference rules to reach the final statement. #### 5. Soundness and Completeness Soundness ensures that proven statements are true, while completeness makes sure that true statements can be proven. ### The Evolution of Proof Systems Proof systems have evolved significantly over the past few decades. To illustrate this, we'll use the classic computer-science problem of graph colouring — assigning colours to vertices in a graph such that no adjacent vertices share the same colour. #### Nondeterministic Polynomial-time (NP) In NP, the prover provides a solution, and the verifier checks its validity. For the graph colouring problem, the prover shows a colouring assignment, and the verifier checks that no adjacent vertices have the same colour. #### Interactive Proof (IP) Introduced in 1985, IP involves a series of interactions between the prover and verifier. The verifier challenges the prover with random questions, and the prover responds until the verifier is convinced. IPs allow probabilistic verification, preserving the prover's privacy. #### Probabilistic Checkable Proofs (PCP) PCP takes non-interactivity to the next level. The proof is transformed into a "proof transcript," and the verifier can randomly query it. This allows for random verification without interaction. #### Interactive Oracle Proof (IOP) IOP combines interaction and oracles (random queries), making interactive proofs more efficient. This model is used in state-of-the-art zero-knowledge proofs. ### Zero-Knowledge Proofs in Cryptography Now, let's delve into the fascinating world of ZKPs. We can categorize them into two main components: #### Information-Theoretic Proof System These proof systems provide soundness and completeness, assuming the verifier is trusted. They make idealized assumptions but need something more to be practical. #### Cryptographic Compiler This is where the magic happens. The compiler removes the idealized assumptions, using cryptographic tools like hash functions or random oracles. The result is a real-world proof system with desirable properties like reduced complexity or added zero-knowledge features. #### Why Separate Them? Modularity is key. By keeping these components separate, we can optimize, analyze, and implement them individually. This separation allows for a variety of real-world proof systems, each with its unique trade-offs. ### Practical Applications: zkSNARKs and zkSTARKs These cryptographic tools are based on ZKPs and are utilized in blockchain technologies. They ensure privacy and scalability in various decentralized applications. ### Conclusion Zero-Knowledge Proofs (ZKPs) are an extraordinary cryptographic tool that enables proof without disclosure. From the foundational concepts of proof systems to the intricate workings of zkSNARKs and zkSTARKs, ZKPs are revolutionizing how we approach privacy and security in the digital age. Whether you're a cryptography enthusiast, a blockchain developer, or simply curious about the world of secure communication, understanding ZKPs is a gateway to exploring the limitless potentials of secure, private, and efficient computing. Keep diving in, keep exploring, and remember that the essence of Zero-Knowledge Proofs lies in the art of proving nothing while revealing everything you need to know. Continue to [Part IV — modular arithmetic](/writing/zk-proofs-part-iv), the engine room behind ZKP soundness and efficiency. ## Zero-Knowledge Proofs: Full Guide, Part II https://lucasmartincalderon.com/writing/zk-proofs-part-ii From Zero to Knowledge: polynomials, how they encode data, relations, and enable efficient comparison in ZKPs. ### Unlocking the Magic of Polynomials Welcome to the world of Zero-Knowledge Proofs (ZKPs), where the power of mathematics allows us to verify facts without revealing the underlying information. A fundamental building block of ZKPs is the mathematical concept known as polynomials. In this article, we'll explore the importance of polynomials, their role in ZKPs, and provide illustrative examples to make these abstract concepts more concrete. ### Understanding Polynomials #### 1. What Is a Polynomial? A polynomial is a mathematical expression consisting of variables, coefficients, and exponents. It can be represented as: `f(x) = aₙ·xⁿ + aₙ₋₁·xⁿ⁻¹ + … + a₁·x + a₀` where the values are the coefficients. Let's plot a simple cubic polynomial: `f(x) = 2x³ − 3x² + x + 4` and observe its graph. The graph represents a cubic polynomial, and its shape is determined by the coefficients and the degree of the polynomial. #### 2. Key Terms in Polynomials **Degree** The degree of a polynomial is the highest power of the variable. For instance, in the polynomial `2x³ − 3x² + x + 4`, the degree is 3. **Coefficients** Coefficients are the numerical values in front of each term. They determine the shape of the graph. **Leading Coefficient** The leading coefficient is the coefficient of the term with the highest degree. It influences the behaviour of the graph as *x* approaches infinity. **Roots** Roots are the values of the variable that make the polynomial equal to zero. They are also referred to as zeros or x-intercepts. **Factorization** Factorization involves expressing a polynomial as a product of simpler polynomials. It helps in finding the roots and simplifying expressions. Let's visualize a quadratic polynomial and its factorization: `f(x) = x² − 5x + 6` `f(x) = (x − 2)(x − 3)` The graph illustrates a quadratic polynomial and its factors. The dashed lines represent the factors `(x − 2)` and `(x − 3)`, whose product gives the original polynomial. #### 3. Fundamental Properties of Polynomials **Division Algorithm** When dividing a polynomial `P(x)` by `G(x)`, you obtain a quotient `Q(x)` and a remainder `R(x)`: `P(x) = G(x) × Q(x) + R(x)` **Factor Theorem** A polynomial `P(x)` is divisible by `(x − a)` if and only if `P(a) = 0`. **Remainder Theorem** If `P(x)` is divided by `(x − a)` with a remainder *r*, then `P(a) = r`. ### Polynomials in Zero-Knowledge Proofs #### Polynomials Can Encode Data Polynomials can represent large amounts of data using coefficients and exponents. For example, a binary number like `10101010` can be encoded as the polynomial `x⁷ + x⁵ + x³ + x`: one term for each bit that is set. #### Polynomials Can Encode Relationships Between Data Polynomial interpolation, such as Lagrange interpolation, allows encoding relationships between data points. By approximating a polynomial that passes through given points, we can represent the relationship between them. #### Polynomials Enable Efficient Data Comparison Polynomial identity testing enables checking whether two pieces of data (represented as polynomials) are the same. Techniques like the Schwartz–Zippel Lemma make this process more efficient. ### Conclusion Polynomials are not just abstract mathematical concepts; they are essential tools in the world of cryptography and Zero-Knowledge Proofs. From encoding information to representing relationships and enabling efficient data comparison, polynomials play a crucial role in securing data privacy. As technology advances, understanding these foundational concepts becomes vital for anyone interested in the field of cryptography and data security. Whether you're a seasoned mathematician or just beginning to explore these concepts, the fascinating world of polynomials and Zero-Knowledge Proofs offers endless opportunities for learning and exploration. Continue to [Part III — proof systems](/writing/zk-proofs-part-iii), where we map out NP, IP, PCP, and IOP — and how zk-SNARKs and zk-STARKs descend from them. ## Zero-Knowledge Proofs: Full Guide, Part I https://lucasmartincalderon.com/writing/zk-proofs-part-i Scalability vs. privacy on public chains, and why zk-SNARKs are the cryptographic bridge between them. ### The Balancing Act of Blockchain: Scalability vs. Privacy One of the most enduring challenges in the blockchain world is striking a balance between scalability and privacy. Critics have always pointed out the limited scalability of major public blockchains like Bitcoin and Ethereum and their relative lack of transaction privacy. But what if there was a way to address both these concerns simultaneously, offering both efficient scaling and robust privacy? Enter the fascinating world of zero-knowledge proofs. ### The Essence of Zero-Knowledge Proofs At its core, a zero-knowledge proof (ZKP) is a cryptographic method that allows one entity to prove to another that a particular statement is true, without revealing any specific information about the statement itself. Let's delve deeper with an analogy. #### Example 1: The Magic Door Imagine a magical door in a cave. Only those who know the secret password can open it. Peggy knows the password and wants to prove this to Victor without revealing the password itself. Peggy enters the cave while Victor waits outside. If she emerges from the other side, it's proof she knows the password. But how can Victor be sure she didn't use some other exit or trick? To ensure fairness, Victor asks Peggy to enter the cave, and then he randomly chooses whether she should come out the same way she entered or from the exit on the other side. Since Peggy doesn't know Victor's choice in advance, the only way she can always emerge correctly is if she genuinely knows the password. This scenario embodies the three crucial properties of ZKPs: 1. **Completeness:** If Peggy knows the password, she can always convince Victor. 2. **Soundness:** If Peggy doesn't know the password, it's nearly impossible for her to deceive Victor consistently. 3. **Zero-knowledge:** Victor learns nothing about the password itself. #### Example 2: The Hidden Tattoo Peggy has a unique tattoo but doesn't want to reveal its design to Victor. She wants to prove its existence without revealing its design. Peggy can cover herself with a large sheet, exposing only a small part of the tattoo. Victor gets a glimpse, verifying its presence, but gains no knowledge about the overall design. ### Technical Deep Dive: zk-SNARKs One of the most notable ZKP constructions is zk-SNARKs, which stands for "Zero-Knowledge Succinct Non-Interactive Argument of Knowledge." The "succinct" part means the proof is short and quick to verify. "Non-Interactive" means there's no back-and-forth communication needed between the two parties. #### zk-SNARKs in Action **Example 3: The Secret Recipe** Peggy claims she knows the secret recipe for a famous dish. The recipe has ten ingredients, but she only wants to prove that she knows the secret ingredient without revealing it. The recipe's uniqueness is such that if you change even one ingredient, the dish tastes entirely different. Peggy prepares the dish and gives it to Victor to taste. Victor, having tasted the original, can confirm that Peggy knows the secret ingredient. But he still doesn't know what that ingredient is. #### How zk-SNARKs Work 1. **Setup:** Generate two keys — a proving key and a verification key. 2. **Prove:** Using the proving key, the prover generates a proof of knowledge without revealing the actual knowledge. 3. **Verify:** Using the verification key, anyone can verify the authenticity of the proof. This entire process ensures the core principles of ZKPs: - **Completeness:** If the statement is true, a verifier will always accept the proof. - **Soundness:** If the statement is false, a verifier will reject the proof. - **Zero-knowledge:** The verifier learns nothing about the actual data or statement. ### Conclusion: The Future is Zero-Knowledge Zero-knowledge proofs, especially zk-SNARKs, are a cornerstone technology, paving the way for scalable and privacy-centric blockchains. Projects like zkSync, Loopring, and Aztec are already leveraging ZKPs to enhance Ethereum's capabilities. While the intricacies of ZKPs can be complex, their potential is clear: a future where blockchains are both scalable and private. This is just the beginning, and as we peel back the layers of this technology, its transformative potential will become even more evident. Continue to [Part II — polynomials](/writing/zk-proofs-part-ii), the mathematical building block underneath every modern ZKP system. ## Neural Networks: Back to Basics, Part I https://lucasmartincalderon.com/writing/neural-networks-back-to-basics-part-i From a one-weight pricing model to gradient descent, the cleanest path I know into the fundamentals. *Study notes. This walk-through follows Jay Alammar’s [A Visual and Interactive Guide to the Basics of Neural Networks](https://jalammar.github.io/visual-interactive-guide-basics-neural-networks/) (2016), with the numbers changed.* ### Introduction Diving into the basics, I realized a need for more beginner-friendly resources. This guide is a response to that need. ### Kickoff with Basics Imagine you're assisting someone in determining if a $500,000 tag for a 2,500 sq ft apartment (about 230 m²) is fair. Without comparisons, it's challenging. So, after some research, you gather data from recent apartment sales. A logical initial approach: find the price per sq ft. This equates to $200 per sq ft. Congratulations — you've just constructed your first, albeit basic, neural network. Not quite AI-chatbot level, but it's the fundamental block. This simplistic diagram represents how the network structures its prediction. The calculation commences from the left input node. The input value transitions rightward, multiplies with the weight, and the result emerges as our output. For a 2,500 sq ft apartment, the multiplication with $200 gives $500,000. At this tier, the prediction is mere multiplication. Before this, determining the weight for multiplication was essential. This weight determination is what we term as the "training" phase. So "training" a neural network essentially means determining the weights to predict. In essence, it's a prediction model. Technically, since the output can range continuously, this model is a "regression model." To visualize this (let's simplify price units from $1 to $1,000, altering our weight to 0.2 instead of 200) we get the same prediction at a different scale. ### Enhancement and Precision Is a mere average of data points the best we can do? Let's refine. For enhancement, we need a clear definition of "better." Evaluating our model against our data points, we get visible errors. In the diagram, yellow represents errors. We aim to minimize this. Here, we note the actual price, predicted price, and their difference. Averaging these differences gives us a measure of the model's error. Negative values, like the −78, pose challenges. Squaring the error eliminates this negativity. Thus, our refinement goal is minimizing this error. This "Mean Square Error" becomes our loss function. Experimenting with various weights, we realize a simple weight variation won't suffice. Introducing a bias, however, can improve the model. With one input and one output (and no hidden layers), it appears as: Here, *W* (weight) and *b* (bias) are determined during training. *X* is our input (square footage), and *Y* is our predicted price. The prediction formula now evolves to: `Y = (W × X) + b` ### Interactive Training Session Why not have a go at training this basic neural network? Your objective: minimize the loss function by adjusting weight and bias. Can you achieve an error below 2,000? A proposed solution, done manually in the command line, lands you within striking distance — but the trial-and-error gets tedious fast. ### Automating the Process Kudos on your manual neural network training. Next, let's explore automation. Consider this autopilot functionality. These buttons apply *gradient descent*, optimizing weight and bias to reduce the loss function. The new graphs help monitor error rates. The essence of training is error reduction. Gradient Descent's direction is informed by calculus. By understanding our loss function and current weight and bias, the function's derivatives guide the adjustments. For a deeper dive into gradient descent, consider Coursera's Machine Learning course's initial lectures. ### Adding Complexity Is apartment size the sole price determinant? Obviously not. Let's incorporate another factor: number of bedrooms. The updated neural network has two weights (one for each input) and one bias. The prediction formula evolves to: `Y = (w₁ × x₁) + (w₂ × x₂) + b` Figuring out *w₁* and *w₂* is intricate. Gradient descent is, once again, our ally. ### Feature Implementation Having explored networks with one or two features, it's evident how to scale. As features increase, weight optimization becomes complex. Feature selection is pivotal and is an art in itself. For a feature-selection example, refer to "A Journey Through Titanic" by Omar El Gabry, which tackles Kaggle's Titanic challenge. ### Categorization Taking our example further, imagine a list of apartments labelled based on size and number of bedrooms. The objective is predicting apartment desirability. Neural networks thus far have been regression-based, providing continuous values. However, often, they're employed for classification, providing discrete outputs like "Good" or "Poor." For instance, an app that labels what a phone camera sees is a classification model. A practical adaptation involves outputting probabilities for each class, like "Good" or "Poor." The *softmax* operation aids in this. For an array input `[3, 5]` into softmax, it might yield `[0.12, 0.88]`, suggesting an 88% probability of the "Poor" label. Softmax outputs are positive, summing to 1, making them apt for probability. The exaggerated difference between outputs aids training. ### Closing Thoughts This guide provides foundational insights into neural networks. As AI and machine learning continue to evolve, understanding these basics empowers us to grasp more intricate concepts and applications. ## AI Expert Retro Talk Part III: LLMs and chatGPT https://lucasmartincalderon.com/writing/ai-expert-retro-llms-and-chatgpt How transformer LLMs actually work, why scale stops mattering, and what InstructGPT changed about steerability. ### What do you mean by LLM? In the realm of artificial intelligence, the term "Large Language Models" often denotes a specific category of deep-learning constructs known as Transformers. These sophisticated models are adept at handling sequential data, whether it's text, images, or time series, and they fall under the broader umbrella of Sequence Models. Many of these Sequence Models can be classified as Language Models, which are designed to learn the probability distribution of subsequent elements in a sequence, such as the next word, pixel, or value. ### So, what are Sequence Models? Sequence models are the subject of Part IV of this series. Continuing on to LLMs, the Transformer architecture stands apart from its antecedents by virtue of its capacity to discern the contextual relationships among values within a sequence, a feat achieved through a mechanism known as (self-)Attention. This contrasts sharply with the Recurrent Neural Network (RNN), which preserves the temporal order by processing each time step sequentially within a sequence. Transformers, on the other hand, are capable of simultaneously reading the entire sequence and selectively focusing on values that precede in time through a process referred to as "masking." This parallel processing not only accelerates training times but also facilitates the handling of larger model parameter sizes. In the early days of Transformers, a model with approximately 100 million parameters was considered "large." However, the landscape has evolved dramatically, with contemporary models boasting an astonishing 500 billion to 1 trillion parameters. Intriguingly, several scholarly articles have identified a significant turning point in Transformer behaviour at around the 100 billion parameter mark. It's worth noting that these colossal models generally exceed the capacity of a single GPU, necessitating the segmentation and distribution of the model across multiple computational nodes. This complexity underscores the transformative power and scale of modern Transformer architectures. Transformers, in the context of deep learning, can be systematically classified into three distinct categories: the "encoder only" design (exemplified by BERT), the "decoder only" structure (as seen in GPT), and the composite "encoder-decoder" architecture (such as T5). 1. **Encoder Only (e.g., BERT):** Typically harnessed for tasks that necessitate a comprehensive understanding of the entire sequence. Sentiment classification is a prime example where the encoder's ability to grasp the full context of a sequence is paramount. 2. **Decoder Only (e.g., GPT):** Contrarily, decoder-only models are particularly suited for tasks that involve text completion, such as finishing a sentence. The decoder's specialization lies in generating coherent continuations of a given text fragment. 3. **Encoder-Decoder Architecture (e.g., T5):** This hybrid design is versatile and can be tailored to address a wide array of problems. Its most renowned application, however, is in the field of language translation, where both encoding and decoding processes are integral to translating text from one language to another. ### And, what, how and why is Attention so important? Covered in depth in [Part V — Attention is All You Need](/writing/ai-expert-retro-attention). Back to LLMs, since the advent of the OG Google's paper on Transformer models and self-attention, we have learned that LLMs have an amazing capacity to **generalize**. Generalization is the capacity of an AI model to produce an accurate and precise inference when feeding on data it has never seen before, and LLMs are almost logarithmically proportional when talking about their accuracy, number of training examples and number of parameters of the LLM. This is called *few-shot AI learners*. However, it is interesting and relevant to know that OpenAI (the company behind chatGPT, powered by GPT-4) has publicly stated that their LLM model can only grow in parameter size so far, before its obvious logarithmic growth and improvement starts halting. ### Research Trends in Large Language Models The landscape of research in Large Language Models (LLMs) has been marked by several prominent trends and innovations. 1. **Scaling Up LLMs:** A significant trend has been the progressive training of increasingly larger LLMs and evaluating their performance on various benchmarks. This trend has sparked debates, such as those presented in the CLIP paper, questioning whether benchmark performance truly reflects a model's generalizability — a nuanced observation known as "The Cheating Hypothesis." 2. **Model Parallelism and Optimization:** The need to train colossal models has necessitated splitting them across multiple GPUs/TPUs. This has been facilitated by techniques from the Megatron paper, innovations in model/pipeline sharding, and tools like DeepSpeed. Additionally, quantization methods have been employed to reduce both memory and computational footprints. 3. **Attention Mechanisms:** Since the traditional self-attention mechanism at the heart of the Transformer exhibits O(N²) space and time complexity, research into more efficient alternatives, such as Flash Attention, has gained traction. Innovations like Alibi have enabled variable context windows, allowing for larger context windows — up to 100k tokens in today's LLMs. 4. **Fine-Tuning Innovations:** Given the sheer size of modern LLMs, there has been a growing interest in fine-tuning them more efficiently. Techniques in Parameter-Efficient Fine-Tuning (PEFT), including Adapters and LoRA, have accelerated this process by reducing the number of parameters to adjust. Coupled with 4- and 8-bit quantization, it's now feasible to fine-tune models on CPUs, a departure from the traditional 16- or 32-bit floats. 5. **Other Research Avenues:** This overview is not exhaustive — there has been substantial research into areas such as LLMs' ability to reproduce information, adversarial attacks, and domain-specific LLMs like Codex (for coding). Early-stage multimodal LLMs, capable of understanding images and text, have also emerged. Moreover, studies like RETRO and webGPT have demonstrated that smaller LLMs can achieve comparable performance to larger models through efficient querying and information retrieval. 6. **Chronological Context:** It's essential to recognize that some of these innovations, such as Flash Attention and LoRA, were developed subsequent to the papers discussed in related sections of the literature. ### InstructGPT: A Pivotal Development in LLM Behaviour The release of the InstructGPT paper marked a seminal advancement in our comprehension of LLM behaviour, particularly in their interaction with natural-language instructions. GPT-3, especially the versions with a substantial number of parameters, had already showcased the ability to respond to natural-language instructions, commonly referred to as "prompts." However, this capability was not without its challenges: 1. **Precision in prompting:** The instructions often had to be meticulously crafted to elicit the desired output. Even slight ambiguities could lead to unexpected or irrelevant responses. 2. **Regurgitation and hallucinations:** The responses generated by the model could either be regurgitated language, often sourced from obscure and unverified parts of the Internet, or entirely fabricated constructs known as "hallucinations." These regurgitated responses could be unfiltered, potentially offensive, untruthful, and generally misaligned with the user's intent. 3. **Underwhelming performance:** Despite the theoretical ability to follow natural-language instructions, the practical application of this capability in LLMs like GPT-3 often fell short of expectations. The inconsistency and unpredictability in responses led to a perception of these models as unreliable or even capricious in their behaviour. ### Steerability and Alignment: Challenges and Innovations in LLMs The training of LLMs to predict subsequent tokens in a sentence has proven to be an effective method for instilling a generalizable understanding of language. By training over extensive corpora (such as the entire Internet) and incorporating various prediction tasks (translation, classification, etc. — referred to as a "mixture of objectives"), researchers can create powerful LLMs capable of few-shot learning. However, this success has not come without challenges. #### 1. Steerability - **User intent mismatch:** Training objectives may not necessarily translate into LLMs accurately following user intent. - **Inconsistent responses:** LLMs may excel at multiple-choice questions or specific tasks but often falter in following user instructions without substantial guidance, especially in zero-shot settings. - **Regurgitation and hallucinations:** Responses may be recycled from previous content, irrelevant ramblings, or confidently presented nonsense. This highlights the issue of steerability — the ability to guide an LLM to produce a desired result. #### 2. Alignment - **Value alignment:** The desire for LLM outputs to reflect specific values (e.g., avoiding racism or homophobia) or meet user quality expectations adds complexity to the alignment problem. - **Open research threads:** Questions surrounding what values an LLM aligns with, how to evaluate alignment, and the feasibility of aligning systems more intelligent than ourselves remain intriguing research areas. #### 3. InstructGPT's Solutions - **Supervised (Instruction) Fine-Tuning (SFT):** A method to refine the model's response to instructions. - **Reinforcement Learning via Human Feedback (RLHF):** A sequential training task to further enhance the model's alignment with human values. By employing these two sequential training tasks, the authors of the InstructGPT paper were able to transform GPT-3 into InstructGPT. #### 4. Key Insights - **Size isn't everything:** The results of the InstructGPT paper revealed that merely increasing the model's size was not a sufficient condition for achieving steerability and alignment. Interestingly, the 175B-parameter GPT-3 "prompted" model performed worse on average than the 1.3B-parameter InstructGPT. ### Experiments #### 1. Instruction Fine-Tuning (SFT) The journey to enhance the output of a generative model logically begins with refining its ability to follow instructions. Methodology: - **Prompt collection:** The authors gathered prompts from real users via their playground API (addressing the cold-start problem) and devised additional prompting tasks. - **Labelling process:** Employing a meticulous selection process, labellers were engaged to create high-quality outputs aligned with Anthropic's 3 Laws: helpful, honest, and harmless (HHH or Triple H). - **Fine-tuning:** Using these gold-standard labels, the authors fine-tuned a GPT model to learn these outputs, a process termed "Supervised Fine-tuning" (SFT). #### 2. Reinforcement Learning via Human Feedback (RLHF) The challenge of imbuing an LLM with a set of values requires a more nuanced approach. Challenges: - **Complexity of human values:** Traditional loss functions, such as cross-entropy, measure a model's belief about data-label probability. Human values, however, are multifaceted and resist encapsulation within a single label. - **Preference encoding:** It may be more practical for humans to encode preferences by comparing multiple LLM outputs rather than explicitly labelling data. RLHF approach: - **Learning preferences:** RLHF aims to teach an AI system preferences by learning a reward function through human interaction and feedback. - **Reward modelling:** This reward model guides the LLM to generate higher-valued outputs via reinforcement learning. It assesses input and output to return a "preferability" score, with the LLM striving to minimize the difference between optimal preference and current output. - **Benefits:** Theoretically, RLHF can reduce an LLM's tendency towards regurgitation by guiding outputs towards optimal answers through incentives, rather than overfitting to specific label distributions. Results with InstructGPT: - **Improved outputs:** InstructGPT demonstrated less toxic, more truthful, and more steerable outputs. - **Catalyst for innovation:** This paper has spurred a wave of new innovations using LLMs. > Note on superalignment: RLHF is not expected to work in the case of superalignment, where the challenge is to teach systems more intelligent than ourselves our values. ### Conclusion The combination of Supervised Fine-Tuning (SFT) and Reinforcement Learning via Human Feedback (RLHF) represents a sophisticated approach to improving LLMs' ability to follow instructions and align with human values. By integrating rigorous labelling, fine-tuning, and reinforcement learning, the authors of the InstructGPT paper have contributed valuable insights and methodologies to the field. These techniques not only enhance the quality and steerability of LLM outputs but also open new horizons for research and innovation in the ever-evolving landscape of artificial intelligence. For those interested in a more detailed exploration of RLHF, HuggingFace's blog post serves as an informative primer. ## AI Expert Retro Talk Part V: Attention is All You Need https://lucasmartincalderon.com/writing/ai-expert-retro-attention A deep dive into attention, from seq2seq's blind spots to self-attention, transformers, and what came next. *Study notes. This overview follows Lilian Weng’s [Attention? Attention!](https://lilianweng.github.io/posts/2018-06-24-attention/) (2018), section by section.* ### 1. Introduction to Attention Attention is a concept in deep learning that is inspired by how humans pay visual attention to different regions of an image or correlate words in a sentence. It allows us to focus on certain areas with "high resolution" while perceiving the surroundings in "low resolution." In AI, attention can be broadly interpreted as a vector of importance weights, helping to predict or infer one element by estimating how strongly it is correlated with other elements. ### 2. The Seq2Seq Model and Its Limitations The seq2seq model, born in the field of language modelling, aims to transform an input sequence to a new one. It consists of an encoder that processes the input sequence and a decoder that emits the transformed output. However, a critical disadvantage of this model is its incapability of remembering long sentences, often forgetting the first part once it processes the whole input. ### 3. Birth of Attention Mechanism for Translation To overcome the limitations of the seq2seq model, the attention mechanism was introduced, particularly to help memorize long source sentences in neural machine translation (NMT). Unlike the traditional method of building a single context vector, attention creates shortcuts between the context vector and the entire source input, allowing for better alignment and memory retention. ### 4. Types and Definitions of Attention Mechanisms Several popular attention mechanisms have been developed, each with unique alignment score functions: - **Content-based attention:** Focuses on content similarity. - **Additive attention:** Uses a feed-forward network for alignment. - **Location-based attention:** Depends on the target position. - **General attention:** Utilizes a trainable weight matrix. - **Dot-product attention:** Based on dot-product calculations. - **Scaled dot-product attention:** Similar to dot-product but with a scaling factor. ### 5. Self-Attention and Its Applications Self-attention, also known as intra-attention, relates different positions of a single sequence to compute a representation of the sequence. It has been shown to be very useful in machine reading, abstractive summarization, or image description generation, allowing for better understanding and correlation between different parts of the content. ### 6. Soft vs Hard Attention Soft attention learns alignment weights over all patches in the source image, making it smooth and differentiable but computationally expensive. Hard attention, on the other hand, selects one patch at a time, making it less computationally intensive but non-differentiable. These two types offer different trade-offs in terms of performance and computational efficiency. ### 7. Global vs Local Attention Global attention is similar to soft attention, attending to the entire input state space. Local attention, an interesting blend between hard and soft, predicts a single aligned position for the current target word and uses a window centred around the source position to compute a context vector. This allows for a more focused and differentiable attention mechanism. ### 8. Neural Turing Machines (NTM) NTM is a model architecture that couples a neural network with external memory storage, mimicking the Turing machine's computational model. It consists of a controller neural network and a memory bank, allowing for more complex and limitless computations. ### 9. Pointer Network The Pointer Network resolves problems where output elements correspond to positions in an input sequence. It applies attention over the input elements to pick one as the output at each decoder step, allowing for more flexible and position-based outputs. ### 10. Transformer Model The transformer model is built entirely on self-attention mechanisms without using sequence-aligned recurrent architecture. It includes components like multi-head self-attention, encoder, and decoder, allowing for more efficient and effective sequence-to-sequence modelling. ### 11. Other Developments - **SNAIL:** Combines self-attention with temporal convolutions, demonstrating good performance in various learning tasks. - **Self-Attention GAN:** Adds self-attention layers into GAN to better model relationships between spatial regions, capturing global dependencies. ### Conclusion Attention plays a crucial and multifaceted role in LLMs and AI. From enhancing prediction and inference to remembering long sequences and capturing relationships between different parts of data, attention mechanisms have revolutionized various domains. Its versatility and effectiveness have led to widespread adoption and continuous exploration, making it a cornerstone in modern AI and deep-learning techniques. Whether in language translation, image recognition, or complex computations, attention provides a nuanced and powerful tool for understanding and processing information. ## Talks and interviews - [ETHDenver: Verifiable AI for Prediction Market Resolution](https://www.youtube.com/watch?v=c37MxSo2jxA): conference talk on how Kash resolves markets with AI. - [Dads Gone Crypto: Are prediction markets coming to social media? The Kash founder story](https://www.youtube.com/watch?v=tUN5ri9ijVU): 45-minute podcast interview. - [The Odds Singapore 2026: Prediction markets roundup, live](https://www.youtube.com/watch?v=b7vihpQ09Bw): 12-minute live session. - [Reality Check with Chesus: Kash, prediction markets you trade from X replies](https://www.youtube.com/watch?v=lNKfx3UIIxU): 68-minute livestream. ## Sources - [PETs4DeFi on CORDIS](https://cordis.europa.eu/project/id/101308999): the European Commission's public record of the programme: funding, dates and partners, Pentestify among them. - [Program on Negotiation at Harvard Law School](https://www.pon.harvard.edu/): where Lucas studied negotiation. ## Profiles - [LinkedIn](https://www.linkedin.com/in/lucasmartincalderon) - [X](https://x.com/lmc_security) - [GitHub](https://github.com/LucasMartinCalderon/LucasMartinCalderon)