I kept seeing the same dumb mistakes in AI-generated code, so I built a local tool to catch them

I’ve been using AI coding tools pretty heavily lately — mostly GROK fast code and some sonnet and haiku. The speed is incredible, and It’s been fun to learn, but I started noticing the same patterns of mistakes showing up in the code.
Not huge architectural disasters. Just the small, annoying things that are easy to miss when you’re moving fast and building with AI:

  • Bare except: blocks that swallow every error
  • Extremely generic function names like process(), handle(), or execute()
  • Code that confidently references imports or error paths that don’t actually exist
    These aren’t hard to spot if you’re carefully reviewing every line, but when you’re accepting a lot of AI suggestions, they slip through more often than I’d like.

Another example

try:

result = db.execute(query)

return result

except:

return None

This was generated code that would have silently hidden database failures in production. The tool caught it immediately.

Why I built something.

I got tired of catching the same classes of issues by hand, so I made a small, local CLI tool to do it for me.
It’s called DriftCode Auditor. It runs entirely on your machine (no code is sent anywhere). I used AI to build it and guide the entire process, but behind it all is a human being. DriftCode Auditor respects .gitignore, and is fast enough to run on real projects.
It currently focuses on three main areas:

  • Privacy risks (hardcoded secrets, PII, etc.)
  • Maintainability issues (long functions, generic names, missing error handling, etc.)
  • Some basic architecture smells
    The goal isn’t to replace thoughtful code review. It’s to act as a quick safety net for the obvious stuff that AI tends to generate.

How to try it

If you want to kick the tires:

pipx install driftcode-auditor

driftcode-auditor –path . –privacy –maintainability

It works on any codebase and gives you a clear report of what it found.
What I’m doing now
I’m currently testing the tool with real users to figure out what’s actually useful. I posted a thread on X earlier today sharing some of the patterns it’s been catching.
If you use AI coding tools regularly, I’d genuinely appreciate it if you tried it on something you’ve been working on and told me what it found (or missed). Even “it didn’t catch anything” is useful feedback.

GitHub: https://github.com/DriftApplied/driftcode-auditor

Discussions (where people can share real examples): https://github.com/DriftApplied/driftcode-auditor/discussions

I’m also happy to take suggestions for new rules or improvements.

Drift Zev
DistortionApplied
X @driftapplied

Weekly Dev Log 2026-W06

🗓️ This Week

  • Made a little more progress in the SwiftUI tutorial🦾
  • Started the journey of building my future portfolio site✈️ First, I created the project files and set up a repository on GitHub. I also started reserching React Router v7 by reading its documentation. I’m moving forward little by little🔥
  • Completed the ContAInment room from the AI Security Learning Path on TryHackMe this week🤖

💡 Thoughts on the ContAInment Room

This room was a hands-on investigation exercise set in a scenario where a company had suffered a security breach, resulting in important data being encrypted and used for blackmail. The goal was to investigate the compromised environment and discover the hidden flags🔎

I felt that this room built nicely on the concepts I learned in the previous AI Forensics room. One thing I especially enjoyed was solving the investigation by using a dedicated AI assistant available inside the victim environment🤖

As I worked through the challenge, I had to think carefully about what looked suspicious and follow clues step by step while actively using Linux commands. It also turned out to be a great review of Linux operations and practical investigation workflows🔥

📱 iOS (SwiftUI)

  • Worked through the SwiftUI tutorial and completed Sections 7 and 8: “Create an Algorithm for Badges”

🌐 Web Development

  • Posted my weekly dev log on Dev.to 📝
  • Created a new React Router v7 project for my future portfolio site.

🔐 Security (TryHackMe)

  • Completed the ContAInment room (part of the AI Security Learning Path) on TryHackMe.

💡 Key Takeaways

📱 SwiftUI Learning

Section 8: Calculate and Show Streaks

  • Learned how to calculate a daily streak by comparing saved dates with the current day.
  • Understood how reversing the array helps process moments from newest to oldest.
  • Learned how map and compactMap can transform Moment objects into simple day offsets like [0, 1, 2].
  • Understood how Calendar.dateComponents calculates date differences in calendar-based units.
  • Learned that multiple moments on the same day should count as a single streak day.
  • Realized that the streak variable represents the next expected day offset during the calculation.
  • Learned that comparing daysAgo == streak is a simple way to detect consecutive days.
  • Understood why using the end of the current day makes streak calculations more stable and predictable.
  • Learned that @ViewBuilder is used to build conditional or multiple-view UI structures, while Group is mainly used to organize existing views or share modifiers without affecting layout.
  • Understood that VStack creates all child views immediately, whereas LazyVStack generates views only when they become visible on screen.
  • Realized that LazyVStack is more suitable for scrollable, data-driven UIs with many or heavy views because it improves memory efficiency and performance.

🌐 Web Development Learning

  • React Router v7 Framework Mode is similar to Remix, so my Remix experience will still be useful.
  • root.tsx, routes.ts, and route files work together to render each page.

🔐 TryHackMe Learning

ContAInment

  • Identified useful indicators from attacker notes and used them to recover encrypted files.
  • Practiced DFIR-style investigation by following clues across logs, archives, and extracted data.
  • Used AI-assisted forensic tools to analyze encoded flag candidates and identify the correct flag.
  • Improved my understanding of how AI systems themselves can become targets in modern cyberattacks.

🚀 Next Week

  • Complete the badge algorithm in the SwiftUI tutorial.
  • Continue posting small articles on Dev.to and start creating Web UI designs in Figma.
  • Continue working on the AI Security Learning Path.

🌈 Goals for This Year

📱 iOS (SwiftUI)

  • Build a solid foundation in SwiftUI and create at least one iOS app.

🌐 Web Development

  • Continue posting learning logs on Dev.to and eventually turn them into a portfolio site using React Router v7.

🔐 Security (TryHackMe)

  • Continue learning cybersecurity on TryHackMe.

The Google I/O 2026 announcement that quietly broke my cost spreadsheet: Gemini’s cache-discount tier

Google I/O 2026 had the headline stuff. Gemma 4 in four sizes. The new agent-friendly Gemini surfaces. Genie. Project Mariner stuff. All worth talking about.

But the announcement that’s actually going to change which agents make sense to build, and which ones I kill on the spreadsheet, isn’t any of those. It’s the cache-discount pricing tier on Gemini 2.5 Flash.

I’m the person who maintains GeminiLens, an open-source observability layer for Gemini agents. Cost calc is a core part of that lib. I had to rewrite the calc the day after the keynote. Here’s why.

The old math

Before I/O 2026, my mental model for a high-frequency Gemini agent looked like this:

  • Input tokens: $0.30 per million
  • Output tokens: $2.50 per million
  • For a research agent that calls Gemini 30+ times in one run with a growing system prompt, the input token cost dominates. Two thirds of every dollar goes to re-sending the same system prompt and tool list over and over.

You can’t fix that with a smaller prompt. The tool list IS the agent. Trimming it makes the agent dumber.

So the choice was usually: either pay the full input bill, or rebuild the agent around a smaller model that’s bad at tools.

The new math

The cache-discount tier (announced at I/O, live in the API now) introduces a third price for input tokens: cached input. Tokens you’ve already sent recently (within the cache TTL window) cost roughly an order of magnitude less than fresh input tokens.

For an agent loop where the system prompt + tool list never changes turn-to-turn, ~95% of “input tokens” on every call after the first one are now cached. The cost graph collapses.

I redid my favorite stress test scenario: a 30-step research agent with a 4K-token system prompt and a 12-tool function-calling schema.

Old pricing New pricing
Avg cost per step $0.0048 $0.0011
Cost per 30-step run $0.14 $0.033
Cost per 100k daily runs $14,400 $3,300

That’s a 4.3x reduction, not from “use a smaller model” or “be smarter about prompts” but from the pricing change alone.

What this means for which agents make sense

I keep a list of “agent ideas I’d love to build but the unit economics kill them.” After the cache-discount tier, three of them moved from no to maybe:

  1. Real-time security alert triage where every new alert kicks off a 20-step Gemini investigation. Old math: ~$1.50 per alert. New math: ~$0.35. Suddenly viable at high alert volumes.
  2. Daily-per-user research digests for a B2B SaaS. Old math: $1.10 per user per day. New math: ~$0.25. Now defensible at $20/seat.
  3. Long-running monitoring agents that wake up every 5 minutes, re-evaluate state, decide nothing changed, go back to sleep. Old math made this look stupid. New math: a fully chatty Gemini agent on a Cron is now cheaper than a small heuristic Lambda.

None of these are flashy. None of them got mentioned in a keynote slide. But for any team building unit-economics-driven Gemini agents, the cache-discount tier is the I/O announcement that changes the model.

What I’m changing in GeminiLens

I had to update three things in GeminiLens the same day:

1. Cost calc now tracks token classes separately.

# before
total_cost = input_tokens * INPUT_PRICE + output_tokens * OUTPUT_PRICE

# after
total_cost = (
    fresh_input_tokens * INPUT_PRICE_FRESH +
    cached_input_tokens * INPUT_PRICE_CACHED +
    output_tokens * OUTPUT_PRICE
)

The naive sum was hiding which calls were cache-hot vs cold. Now the JSONL audit log carries fresh_input_tokens and cached_input_tokens as separate fields. The Streamlit dashboard renders a per-call cache-hit ratio.

2. Dashboard now shows “could-have-been-cached” warnings.

If I see a 30-step run where every call has zero cached tokens, that’s a bug — the cache TTL is probably set wrong or the prompt is being reshuffled. Now flagged as a warning.

3. Cost-per-run estimator splits cold-start vs steady-state.

For agent loops, the first call is cold (full input price), and steady-state is hot. Reporting the average flattens the picture and makes optimization decisions harder. The new dashboard shows both numbers separately.

The under-the-radar thing

Most I/O coverage I’ve seen frames the cache tier as “an API optimization” — paragraph 4 of a TechCrunch post, two-thirds down the Gemini docs page. It’s actually a unit-economics step change for one specific shape of agent: the kind where the prompt stays large and the loop stays long.

If you’re shipping that kind of agent, redo your spreadsheet. The math you had on Friday May 16 is no longer the math.

This is my entry for the Google I/O 2026 Writing Challenge. I work on open-source AI agent reliability tooling under @MukundaKatta. GeminiLens is on PyPI: pip install geminilens.

Construyendo la PC de Escritorio de tus Sueños

En el corazón de una bulliciosa ciudad, enclavado entre rascacielos imponentes y el murmullo de la vida cotidiana, existe un tranquilo santuario para los creadores: un espacio donde las ideas cobran vida a través del poder de la tecnología. Para muchos, este santuario es una computadora de escritorio construida a medida, una máquina adaptada a las exigencias únicas de la programación y la animación. Construir semejante máquina no es solo una tarea técnica; es un viaje de descubrimiento, creatividad y empoderamiento.

Una Máquina a la Altura de tus Ambiciones

Toda gran creación comienza con una visión. Para César, un aspirante a desarrollador de software y animador, esa visión era una computadora de escritorio capaz de manejar todo, desde la compilación de código complejo hasta la renderización de animaciones en alta definición. César sabía que las computadoras comerciales, aunque convenientes, suelen tener limitaciones: capacidad de actualización reducida, software innecesario preinstalado y componentes que no se adaptan del todo a las exigencias de su trabajo.
La idea de construir una PC personalizada resultaba intimidante al principio. La sola idea de seleccionar componentes individuales, ensamblarlos y asegurarse de que todo funcionara a la perfección parecía una tarea monumental. Pero a medida que César se adentraba en el mundo de las construcciones personalizadas, se dio cuenta de que este proceso no se trataba solo de crear una máquina, sino de comprender las herramientas de su oficio y crear algo verdaderamente propio.

Eligiendo las Herramientas Adecuadas para el Trabajo

El primer paso en el viaje de César fue seleccionar los componentes. Aquí fue donde comenzó la magia. Cada parte de la computadora cumplía un papel crucial, y elegir las correctas requería una consideración cuidadosa.
La CPU (Unidad Central de Procesamiento) era el cerebro de la operación. Para la programación y la animación, César necesitaba un procesador capaz de manejar la multitarea y los cálculos complejos. Optó por una CPU de alto número de núcleos, garantizando un rendimiento fluido incluso al ejecutar múltiples máquinas virtuales o renderizar modelos 3D intrincados.
Luego llegó la GPU (Unidad de Procesamiento Gráfico), el motor de trabajo para la animación y el renderizado. César eligió una tarjeta gráfica potente capaz de manejar el renderizado en tiempo real y las tareas aceleradas por GPU. Esto sería esencial para crear animaciones fluidas y visualizar escenas complejas.
La memoria, o RAM, era otro componente crítico. Los entornos de programación y el software de animación suelen consumir grandes cantidades de memoria, por lo que César seleccionó una cantidad generosa de RAM de alta velocidad para asegurarse de que su sistema pudiera manejar incluso los proyectos más exigentes.
El almacenamiento era igualmente importante. César se decidió por una combinación de un SSD rápido para el sistema operativo y las aplicaciones de uso frecuente, y un HDD de mayor capacidad para almacenar archivos de proyectos y archivos históricos. Este equilibrio entre velocidad y capacidad mantendría su flujo de trabajo eficiente y organizado.

Un Trabajo de Amor

Con todos los componentes en mano, César comenzó el proceso de ensamblaje. Aquí fue donde la visión comenzó a tomar forma física. La tarjeta madre, una extensa placa de circuitos, se convirtió en la base de la construcción. Con cuidado, César instaló la CPU, aplicó pasta térmica y aseguró el disipador. Cada paso requería precisión y paciencia, pero el proceso era profundamente satisfactorio.
La tarjeta gráfica, una pieza de hardware elegante e imponente, fue colocada en su ranura. La unidad de fuente de poder, con su laberinto de cables, fue meticulosamente conectada a cada componente. El gabinete, elegido por su diseño elegante y su excelente flujo de aire, albergaba todo ordenadamente, con espacio para futuras mejoras.
Cuando César conectó los cables finales y encendió el sistema por primera vez, una sensación de logro lo invadió. La máquina cobró vida con un suave zumbido, sus ventiladores giraban silenciosamente y el monitor parpadeó al encenderse, mostrando la pantalla del BIOS. Fue un momento de triunfo: un testimonio de su arduo trabajo y dedicación.

Una Herramienta para la Creatividad y la Innovación

Para César, la computadora de escritorio personalizada era más que una simple computadora: era una herramienta para la creatividad y la innovación. La programación se volvió más rápida y eficiente, con el sistema manejando sin esfuerzo bases de código complejas y entornos virtuales. Los proyectos de animación, antes obstaculizados por tiempos de renderizado lentos, ahora fluían sin problemas, permitiendo a César concentrarse en el proceso creativo en lugar de las limitaciones técnicas.

El viaje de construir la computadora de escritorio también había profundizado la comprensión de César sobre la tecnología en la que dependía. Conocía cada componente, cada conexión y cada posible ruta de actualización. Este conocimiento le dio confianza y un sentido de pertenencia sobre sus herramientas.

Una Máquina que Crece Contigo

Una de las mayores ventajas de una computadora de escritorio personalizada es su capacidad de evolucionar. A medida que las habilidades y proyectos de César crecían, su máquina también podía hacerlo. Se podían agregar nuevos componentes, reemplazar piezas obsoletas y optimizar el sistema para nuevos desafíos. Esta flexibilidad garantizaba que la computadora de escritorio seguiría siendo un compañero confiable durante años.
Al final, construir una computadora de escritorio personalizada es más que un simple proyecto técnico: es un viaje de empoderamiento, creatividad y crecimiento. Para César, y para incontables personas más, es una forma de tomar el control de sus herramientas, superar los límites de lo posible y crear algo verdaderamente extraordinario.

And so, in that quiet sanctuary, surrounded by the hum of their custom-built machine, Cesar continued to create, innovate, and dream. The journey of building his desktop had not only given them a powerful tool but also a deeper connection to the art and science of his craft.

Log Parsing with AI at Bronto

Bronto LLM-powered log parser

Authored by Gary Nicholls

This post follows on from our AWS Nova log benchmarking article, where we explored how smaller LLMs perform on log analysis tasks. That earlier post highlighted that LLMs are surprisingly good at parsing logs. While that work focused on understanding logs, this post tackles an earlier step: automatically structuring logs using AI.

Logging Origins

Logs are one of the oldest — and still most valuable — forms of observability. Mainframes and early Unix systems were already using logs to record system activity, with tools like syslog dating back to the early 1980s.

Even as systems have become more distributed and complex, logs remain foundational, especially for investigating issues when things go wrong. Logs are typically written to local files before being shipped to modern observability platforms using agents like OpenTelemetry or Fluent Bit.

Why So Many Formats?

The OpenTelemetry (OTel) project is encouraging the adoption of structured JSON logs — and that’s a good thing. Structured logs are easier to search, more human-readable, safer to manipulate, and more cloud-native.

But the reality isn’t that simple. Many systems still generate unstructured or semi-structured logs where key=value pairs are embedded inside free-text messages. And even among structured formats, things vary wildly — timestamps alone appear in dozens of different formats.

Logs reflect the unique fingerprint of each tech stack:

  • syslog — still widely used, with quirks in its timestamp formatting
  • Apache — uses the Common Log Format
  • nginx — has its own custom variant
  • Java apps — use logback, log4j, or slf4j
  • AWS services — often emit structured JSON or a hybrid of text and JSON

With no single standard, Bronto set out to solve the problem in an innovative way — using AI to generate parsers automatically, reducing the toil and complexity that users typically face.

Automated Log Parsing

Parsing logs in real time is a performance-critical operation. When ingesting millions of events per second, every millisecond counts. Regex-based parsing can be complex and hard to maintain, requiring expertise in tools like Grok or Dissect — and can become a bottleneck at scale when applied indiscriminately.

At Bronto, we use a multi-layered approach that separates offline detection from online parsing. Online parsing happens in real time as part of the ingestion pipeline; offline detection occurs outside the pipeline with a short delay. This hybrid approach ensures speed without sacrificing flexibility, while reducing user toil.

Layer 1: Curated Java Parsers

We maintain a library of high-performance Java-based parsers, optimized for the most common formats seen at high volumes across multiple customers. These are purpose-built for speed and designed to fail fast if they encounter a log that doesn’t match their expected format.

After applying a Java parser, we run additional lightweight processors to normalize key fields:

  • Timestamp parser — auto-detects and normalizes varied timestamp formats
  • Log level parser — maps diverse severity keywords into five standard levels
  • KVP parser — extracts key=value pairs from the message or body, even if only present in some events

Layer 2: Dissect and Grok Fallback

For less common but still important formats, we fall back to Dissect or Grok:

  • Dissect — fast and great for structured, delimiter-based logs
  • Grok — more flexible, supports regex-based parsing, but comes at a performance cost

Bronto maintains a large database of both dissect and grok patterns. Due to their runtime cost, we don’t attempt to apply every pattern to every event online. Instead:

  1. We sample log events offline
  2. Match them against our full pattern library
  3. If a match is found, we automatically assign a parser hint to the dataset
  4. Future events in that dataset are parsed using the matched pattern
  5. We gather metrics on parse quality per dataset and periodically revalidate hints

Layer 3: AI-Generated Parsing

When we encounter unknown or proprietary formats, other tools might require users to handcraft regexes through a UI. At Bronto, we let AI do the work.

Bronto LLM-powered log parser

When enabled, we send a sample of the dataset to an internal AI engine that analyzes the log structure and generates a custom dissect pattern. We test the pattern against a wider sample. If it matches a high percentage of events, we present the pattern and sample results to the user — they can tweak field names if desired — and once approved, the parser is saved and applied automatically to all future events in that dataset.

A Worked Example

Suppose your application logs look like this:

Raw unstructured application logs

After analyzing hundreds of lines, the AI generates a dissect pattern:

AI-generated dissect pattern

The parsed result looks like this:

app_name timestamp log_level message
APP01 2024-07-03 12:50:59 WARN Invalid sessionId: sessionId=expired
APP01 2024-07-03 12:49:41 INFO Authentication token issued
APP01 2024-07-03 12:48:27 INFO User logout: userId=14141
APP01 2024-07-03 12:47:10 INFO New login attempt
APP01 2024-07-03 12:45:37 INFO Form submitted: formId=contact-us

The KVP parser then further extracts fields like sessionId, userId, and formId from the message value.

Full AI log parser pipeline diagram

Under the Hood: AWS Bedrock

We use AWS Bedrock as a managed service to access LLMs (including Claude). Our infrastructure chooses the most appropriate model for each application and sends structured prompts — for example, instructing the LLM which patterns to avoid and how to handle keys like timestamps. The user doesn’t have to worry about models or prompts; they just use the application.

Bedrock also provides important SaaS-grade guarantees:

  • Built-in safeguards to detect and filter harmful content
  • Never stores or uses our data to train models
  • All data remains within the AWS network
  • Works seamlessly with Lambda and S3 — no platform rearchitecting required

Looking Ahead

At Bronto we believe parsing should be fast, accurate, and hands-free. Today we generate dissect patterns using AI. Soon we’ll be generating Grok patterns too — bringing AI to even more complex and less structured formats.

As OTel continues to push for JSON-based structured logging, the hope is that log parsing becomes a less painful problem over time. But until then, automated, adaptive parsing isn’t just a convenience — it’s a necessity.

Summary

Bronto combines curated Java parsers, flexible Dissect/Grok matching, and AI-powered pattern generation into a unified pipeline for parsing any log format, structured or otherwise.

If your logs are weird or messy — we’ve got you.

Explore Bronto’s AI Features

代理模式深度指南:构建控制访问的艺术

代理模式深度指南:构建控制访问的艺术

在软件架构中,代理模式是一种结构型设计模式,它为另一个对象提供一个替代品或占位符,以控制对该对象的访问。本文将深入探讨代理模式的原理、实现方式和实战应用。

为什么需要代理模式?

想象一下,你需要访问一个远程服务。每次直接调用远程对象都会产生网络延迟。但如果你能在本地放置一个”替身”,让它处理一些常见请求,只有必要时才真正访问远程服务,性能将大幅提升。

这就是代理模式的核心思想:用一个中介来控制对真实对象的访问。

代理模式的组成

代理模式包含四个核心角色:

  1. Subject(抽象主题):定义了 RealSubject 和 Proxy 的公共接口
  2. RealSubject(真实主题):真正执行业务逻辑的对象
  3. Proxy(代理):持有 RealSubject 的引用,在需要时创建真实对象
  4. Client(客户端):通过 Proxy 访问真实对象

代理模式的类型

1. 远程代理 (Remote Proxy)

为远程对象在本地创建一个代理,隐藏网络访问细节。适用于需要调用分布式服务的场景。

客户端 → 本地代理 → 网络 → 远程服务

2. 虚代理 (Virtual Proxy)

延迟加载,只在真正需要时才创建开销大的对象。这就像网购时的”待发货”状态——先显示占位,等需要时才真正加载。

class VirtualProxy Image:
    def __init__(self, url):
        self.url = url
        self._real_image = None

    def display(self):
        # 首次调用时才加载真实图片
        if not self._real_image:
            self._real_image = RealImage(self.url)
        self._real_image.display()

3. 保护代理 (Protection Proxy)

控制对真实对象的访问权限,在调用前进行身份验证。这类似于公司门禁系统——检查访客是否有权限进入。

4. 智能引用代理 (Smart Reference Proxy)

在访问对象时附加额外操作,比如:

  • 记录调用次数
  • 缓存计算结果
  • 懒加载关联对象

5. 缓存代理 (Cache Proxy)

为重复访问的结果提供缓存,避免重复计算。这就像浏览器的缓存机制——首次加载后保存在本地,后续直接使用。

Python 实现示例

from abc import ABC, abstractmethod
import time

# 抽象主题
class Image(ABC):
    @abstractmethod
    def display(self):
        pass

# 真实主题
class RealImage(Image):
    def __init__(self, filename):
        self.filename = filename
        self._load_from_disk()

    def _load_from_disk(self):
        print(f"正在加载图片: {self.filename}")
        time.sleep(1)  # 模拟加载时间
        print("加载完成!")

    def display(self):
        print(f"显示图片: {self.filename}")

# 虚拟代理
class ProxyImage(Image):
    def __init__(self, filename):
        self.filename = filename
        self._real_image = None

    def display(self):
        if self._real_image is None:
            self._real_image = RealImage(self.filename)
        self._real_image.display()

# 使用示例
print("=== 第一次显示 ===")
img = ProxyImage("photo.jpg")
img.display()

print("n=== 第二次显示 ===")
img.display()

运行结果:

=== 第一次显示 ===
正在加载图片: photo.jpg
加载完成!
显示图片: photo.jpg

=== 第二次显示 ===
显示图片: photo.jpg

代理模式 vs 装饰器模式

特性 代理模式 装饰器模式
目的 控制访问 动态添加功能
关系 替代真实对象 包装真实对象
创建时机 预先创建 运行时包装
客户端感知 无缝替换 功能增强

实际应用场景

1. 数据库连接池

连接池本身就是一种代理模式——预先创建一批连接,客户端从代理获取连接,用完归还,而不是每次都创建新连接。

2. API 限流

在高并发系统中,使用代理实现 API 限流,保护后端服务:

class RateLimitedProxy:
    def __init__(self, real_service, max_requests, time_window):
        self.real_service = real_service
        self.max_requests = max_requests
        self.time_window = time_window
        self.requests = []

    def call(self, *args, **kwargs):
        now = time.time()

        # 清理过期请求记录
        self.requests = [t for t in self.requests if now - t < self.time_window]

        if len(self.requests) >= self.max_requests:
            raise Exception("请求过于频繁,请稍后再试")

        self.requests.append(now)
        return self.real_service.execute(*args, **kwargs)

3. 考试系统防作弊

在在线考试系统中,代理可以:

  • 检测切屏次数
  • 限制复制粘贴
  • 记录异常行为

4. 微服务健康检查

代理可以监控下游服务状态,在服务不可用时返回缓存数据或降级响应。

总结

代理模式是一种强大的架构工具,它的核心价值在于:

  1. 解耦 – 将访问逻辑与业务逻辑分离
  2. 增强 – 可以无感地添加日志、缓存、限流等功能
  3. 控制 – 实现访问控制、权限验证
  4. 优化 – 通过懒加载和缓存提升性能

掌握代理模式,让你在设计系统时多一件利器!

下篇预告:策略模式 (Strategy Pattern) – 让算法 interchangeable 的艺术

如果你对这个系列感兴趣,欢迎关注并留言讨论你想了解的设计模式!

💡 提示:合理使用代理模式可以显著提升系统性能和安全性,但切记不要过度设计。只有当真正需要控制访问时,才考虑使用代理。

Amazon Q Developer CLI ahora es Kiro CLI — ¿Qué cambió y por qué importa?

Amazon Q Developer CLI ahora es Kiro CLI — ¿Qué cambió y por qué importa?

Si llevas un tiempo en el ecosistema AWS y usas herramientas de desarrollo con IA, probablemente ya notaste el cambio: Amazon Q Developer CLI ya no existe como tal. Ahora se llama Kiro CLI. Y no, no es solo un rebrand de nombre — es un cambio de filosofía completo.

Vamos a explorar qué pasó, qué cambió realmente, y por qué creo que esto importa más de lo que parece.

Un poco de contexto: ¿qué era Amazon Q Developer CLI?

Amazon Q Developer era el asistente de IA de AWS para desarrolladores. Tenía una versión en el IDE (VS Code, JetBrains), una versión en la consola de AWS, y también una CLI que te permitía interactuar con tu entorno desde la terminal usando lenguaje natural.

La idea era buena: preguntarle a un agente directamente desde tu terminal cosas como “¿qué instancias EC2 tengo corriendo en us-east-1?” o “genera un script para limpiar buckets S3 sin versioning”. Útil, pero limitado en su enfoque — era básicamente un chatbot en tu terminal.

Entonces, ¿qué es Kiro?

Kiro es un IDE agéntico construido sobre VS Code, lanzado por AWS. Pero lo que muchos no saben es que también tiene una CLI — Kiro CLI — que reemplaza directamente a Amazon Q Developer CLI.

Lo interesante es que Kiro no es solo “Q con otro nombre”. El cambio refleja una evolución real en cómo AWS piensa las herramientas de desarrollo:

Amazon Q Developer CLI Kiro CLI
Asistente conversacional en terminal Agente con contexto del proyecto
Respuestas puntuales Spec-driven + MCP-driven + Steering-driven
Foco en queries rápidas Foco en workflows completos
Sin memoria de proyecto Entiende tu arquitectura y convenciones
Comando: q chat Comando: kiro-cli chat

La idea aquí es que Kiro no solo responde preguntas — razona sobre tu proyecto, lee tus steering files, se conecta a herramientas externas vía MCP, y actúa en consecuencia.

El cambio más importante: de “asistente” a “agente”

En la práctica esto significa que Kiro CLI opera con capacidades que Amazon Q Developer CLI nunca tuvo de forma nativa:

Core Features de Kiro CLI

  • Interactive Chat — Conversaciones en lenguaje natural directamente en tu terminal con kiro-cli chat. Puede leer y escribir archivos, ejecutar comandos, y razonar sobre tu código.

  • Custom Agents — Puedes crear y desplegar agentes especializados para tus workflows específicos. No estás limitado al agente genérico.

  • MCP Integration — Conecta herramientas y fuentes de datos externas a través del Model Context Protocol. Esto es enorme — puedes conectar Kiro CLI a servidores MCP de CloudWatch, MSK, OpenSearch, Okta, y muchos más.

  • Smart Hooks — Automatiza workflows con hooks inteligentes que se ejecutan antes o después de comandos específicos.

  • Agent Steering — Guía al agente con las mejores prácticas y preferencias de tu equipo usando steering files. Esto es lo que hace que Kiro entienda tu contexto, no solo el contexto genérico.

  • Auto Complete — Sugerencias inteligentes de comandos con contexto mientras escribes en la terminal.

# Antes con Amazon Q Developer CLI
q chat "lista mis funciones Lambda en us-east-1"

# Ahora con Kiro CLI — con contexto de proyecto y MCP
kiro-cli chat
> revisa las funciones Lambda del proyecto y sugiere optimizaciones basándote en las métricas de CloudWatch

La diferencia no es solo sintáctica. Kiro sabe qué proyecto es, tiene acceso a tus herramientas vía MCP, y puede actuar sobre eso.

¿Cómo instalar Kiro CLI hoy?

La instalación es directa:

# macOS / Linux
curl -fsSL https://cli.kiro.dev/install | bash

# Windows (PowerShell)
irm 'https://cli.kiro.dev/install.ps1' | iex

# Verificar instalación
kiro-cli --version

Una vez instalado, empezar es así de simple:

# Navega a tu proyecto
cd mi-proyecto

# Inicia Kiro CLI
kiro-cli

# O directamente al chat
kiro-cli chat

Otros comandos útiles

# Traducir lenguaje natural a comandos bash
kiro-cli translate "muestra los últimos 10 logs de mi función Lambda"

# Habilitar sugerencias inline (requiere zsh)
kiro-cli inline enable

# Deshabilitar sugerencias inline
kiro-cli inline disable

Lo interesante es que kiro-cli translate convierte tu instrucción en el comando bash correspondiente sin ejecutarlo — tú decides si lo corres o no. Perfecto para aprender comandos complejos de AWS CLI.

Kiro CLI en CloudShell

Si no quieres instalar nada localmente, Kiro CLI ya viene disponible en AWS CloudShell. Solo abre CloudShell y ejecuta kiro-cli.

Las sugerencias inline en CloudShell requieren Z shell:

# Cambiar a zsh en CloudShell
zsh

# Las sugerencias inline se habilitan automáticamente
# Para deshabilitarlas:
kiro-cli inline disable

Agent Steering: dale contexto persistente a Kiro CLI

Esta es una de las features más importantes de Kiro CLI y la que marca la diferencia real con lo que teníamos en Amazon Q Developer CLI. Los steering files son archivos markdown que le dan a Kiro conocimiento persistente sobre tu proyecto, tu stack, y las convenciones de tu equipo.

La idea aquí es simple: en vez de re-explicar tu proyecto cada vez que abres una sesión, escribes un steering file una vez y Kiro lo lee automáticamente en cada interacción.

¿Qué poner en un steering file?

Un steering file es un .md que vive en tu proyecto (típicamente en .kiro/steering/) y puede contener:

  • Stack tecnológico — qué lenguajes, frameworks y servicios usas
  • Convenciones del equipo — naming conventions, patrones de diseño, estructura de carpetas
  • Contexto de infraestructura — nombres de instancias, ubicación de logs, usuarios del sistema
  • Requisitos de compliance — estándares de seguridad, accesibilidad, auditoría
  • Reglas de negocio — lógica específica de tu dominio que el agente debe respetar

Ejemplo real: steering file para un proyecto serverless

# Project Context

## Stack
- Runtime: Python 3.12 on AWS Lambda
- API: Amazon API Gateway (REST)
- Database: Amazon DynamoDB (single-table design)
- IaC: AWS CDK (Python)

## Conventions
- All Lambda handlers go in `src/handlers/`
- Business logic goes in `src/services/` — never in handlers
- Use structured logging with aws-lambda-powertools
- DynamoDB access patterns use PK/SK with GSI1

## Security
- All API endpoints require IAM authorization
- No hardcoded credentials — use environment variables from Secrets Manager
- Input validation on every handler entry point

Lo que hace esto particularmente poderoso es que Kiro CLI usa este contexto en cada interacción. Si le pides que genere un nuevo endpoint, va a seguir tus convenciones automáticamente — handlers en src/handlers/, lógica en src/services/, con powertools y validación de input. Sin que tengas que repetirlo.

Steering files en la práctica

El blog de AWS sobre Oracle EBS con Kiro CLI muestra un caso real: usan steering files para darle a Kiro el conocimiento de su entorno Oracle — patrones de nombres de instancias, usuarios del OS, ubicación de logs y scripts. Así, cuando preguntan “¿está sano el concurrent manager?”, Kiro ya sabe dónde buscar sin que se lo expliquen cada vez.

Para equipos, esto es oro. Un nuevo developer se une, clona el repo, y Kiro CLI ya tiene todo el contexto del proyecto en los steering files. La curva de onboarding se reduce dramáticamente.

Spec-Driven Development: ¿disponible en Kiro CLI?

Acá hay que ser claros porque es una pregunta que muchos se hacen. Spec-Driven Development es una feature del Kiro IDE, no de Kiro CLI.

Según la documentación oficial de Kiro, las Specs viven bajo la sección de documentación del IDE (/docs/specs/), y no aparecen en la sidebar de la CLI. La CLI tiene: Chat, Custom Agents, MCP, Hooks, Steering, Autocomplete, y Headless — pero no Specs.

¿Qué es Spec-Driven Development?

Para los que no lo conocen, es el workflow estrella de Kiro IDE. Funciona así:

  1. Le describes tu idea al agente en lenguaje natural
  2. Kiro genera requirements estructurados (en formato EARS)
  3. Kiro crea un design document con arquitectura, modelos de datos, APIs
  4. Kiro produce un plan de implementación con tareas concretas y ordenadas
  5. Kiro ejecuta cada tarea — escribe código, tests, documentación

Cada spec genera tres archivos clave: requirements.md, design.md, y tasks.md. Hay dos tipos de specs: Feature Specs (para funcionalidades nuevas) y Bugfix Specs (para diagnosticar y corregir bugs).

¿Por qué no está en la CLI?

Mi lectura es que Spec-Driven Development requiere una experiencia visual que la terminal no puede ofrecer fácilmente — la navegación entre archivos de spec, la vista de progreso de tareas, y la interacción con el design document son inherentemente visuales. La CLI está optimizada para workflows más directos: chat, automatización, MCP, y headless.

¿Qué usar entonces?

Necesidad Herramienta
Desarrollar features completas con specs Kiro IDE
Chat agéntico desde la terminal Kiro CLI
Automatización y CI/CD Kiro CLI (headless)
Conectar herramientas externas vía MCP Kiro CLI o Kiro IDE
Steering files para contexto de equipo Kiro CLI o Kiro IDE
Troubleshooting rápido de AWS Kiro CLI

Mi recomendación: usa ambos. Kiro IDE para desarrollo de features con specs, y Kiro CLI para todo lo que haces en la terminal — troubleshooting, automatización, operaciones, y CI/CD. Los steering files funcionan en ambos, así que tu contexto de proyecto se comparte.

MCP: lo que hace a Kiro CLI realmente poderoso

El Model Context Protocol es un estándar abierto que permite a agentes de IA conectarse de forma segura con herramientas externas, fuentes de datos y servicios. En la práctica esto significa que puedes extender las capacidades de Kiro CLI conectándolo a servidores MCP especializados.

Algunos ejemplos reales que ya existen:

Servidor MCP Qué hace
CloudWatch MCP Consulta métricas, logs y alarmas con lenguaje natural
Amazon MSK MCP Administra clusters de Kafka — topics, configuraciones, health
AWS Diagram MCP Genera diagramas de arquitectura AWS desde prompts
OpenSearch MCP Busca índices, inspecciona estado del cluster, diagnósticos
Okta MCP Gestión de identidades — usuarios, grupos, permisos
AWS Documentation MCP Busca y lee documentación de AWS en contexto

La configuración de un servidor MCP se hace en ~/.kiro/settings/mcp.json. Una vez configurado, Kiro CLI tiene acceso a las herramientas del servidor y las usa automáticamente cuando son relevantes para tu pregunta.

Lo que hace esto particularmente poderoso es que puedes combinar múltiples servidores MCP. Imagina preguntarle a Kiro CLI: “¿por qué mi aplicación está lenta?” y que automáticamente consulte CloudWatch para métricas, OpenSearch para logs, y te dé un diagnóstico completo — todo desde tu terminal.

Los métodos de login — esto es clave

Acá es donde la cosa se pone interesante de verdad, porque Kiro CLI hereda el modelo de autenticación de Amazon Q Developer pero con matices que importan. Hay cuatro formas de conectarte, y cada una te da acceso a cosas diferentes:

1. Builder ID (Free) — para empezar rápido

Es la forma más simple. Te creas un AWS Builder ID gratis (con tu email, Google, Apple, GitHub o Amazon) y listo, ya puedes usar Kiro CLI y el IDE.

La limitación: tienes límites mensuales de uso y solo funciona en el IDE y la CLI. No tienes acceso a la consola de AWS ni a features avanzados. Pero para proyectos personales y exploración, es más que suficiente.

2. Builder ID + Pro — más límites, tu propia cuenta AWS

Acá es donde empieza a ponerse bueno. Puedes hacer upgrade de tu Builder ID al tier Pro conectándolo a tu propia cuenta de AWS. Esto te da límites de uso mucho más altos.

# Inicia chat con Kiro CLI
kiro-cli chat

# Dentro del chat, escribe:
/subscribe
# Esto abre la consola de AWS para confirmar la suscripción Pro

El punto clave es que con Builder ID Pro tienes límites más altos, pero no todas las features Pro. Algunas features avanzadas solo están disponibles vía IAM Identity Center.

3. IAM Identity Center (Free) — para equipos y organizaciones

Si tu empresa ya usa IAM Identity Center (antes AWS SSO), puedes autenticarte con tu identidad corporativa. Esto te da acceso a la consola de AWS, apps y websites de AWS — algo que Builder ID no puede hacer.

Ideal si tu admin ya configuró el Identity Center en la organización.

4. IAM Identity Center + Pro — el combo completo 🔥

Y acá está el gold standard. Tu admin te suscribe a Amazon Q Developer Pro vía IAM Identity Center, y tienes acceso a todo: CLI, IDE, consola, apps de AWS, features avanzados, límites altos, y control empresarial.

Lo que hace esto particularmente poderoso es que tu empresa tiene control total: puede suscribir usuarios en bulk, trackear uso, cancelar suscripciones, y tú como developer tienes la experiencia completa en todos los canales.

La guía rápida de acceso

🆓 Builder ID — Free

✅ CLI · ✅ IDE · ❌ Consola AWS · ❌ Features Pro
→ Para empezar rápido con proyectos personales

💰 Builder ID — Pro

✅ CLI · ✅ IDE · ❌ Consola AWS · ⚠️ Features Pro parciales
→ Límites más altos, pero no el suite completo

🏢 IAM Identity Center — Free

❌ CLI · ❌ IDE · ✅ Consola AWS · ❌ Features Pro
→ Solo consola, ideal si tu admin aún no activó Pro

🔥 IAM Identity Center — Pro

✅ CLI · ✅ IDE · ✅ Consola AWS · ✅ Features Pro completos
→ La experiencia completa — el gold standard

Mi recomendación sincera: si eres developer individual, empieza con Builder ID Free y cuando sientas los límites, haz upgrade a Pro con tu cuenta AWS. Si estás en una empresa, pídele a tu admin que configure IAM Identity Center con Pro — es la experiencia más completa y además puedes usarlo desde Kiro IDE con toda la potencia.

Headless Mode: Kiro CLI en CI/CD

Una capacidad nueva que no existía en Q Developer CLI es el modo headless — puedes ejecutar prompts de forma no interactiva usando API keys. Esto abre la puerta a integrar Kiro CLI en pipelines de CI/CD.

En la práctica esto significa que puedes automatizar tareas como:

  • Revisión de código automatizada en PRs
  • Generación de documentación en cada merge
  • Análisis de seguridad como paso del pipeline
  • Generación de tests para código nuevo

¿Debería migrar ya?

Sí, y sin dudarlo. Amazon Q Developer CLI ya no recibe actualizaciones activas. Todo el desarrollo está en Kiro CLI.

Pero más allá de la migración técnica, lo que me parece más valioso es el cambio de mentalidad que propone Kiro: dejar de usar la IA como un buscador glorificado y empezar a usarla como un agente que entiende tu contexto, se conecta a tus herramientas, y trabaja contigo en workflows reales.

La migración en sí es simple:

# 1. Instalar Kiro CLI
curl -fsSL https://cli.kiro.dev/install | bash

# 2. Donde antes usabas 'q chat', ahora usas:
kiro-cli chat

# 3. Donde usabas 'q translate', ahora:
kiro-cli translate "tu instrucción aquí"

El takeaway principal

El cambio de Amazon Q Developer CLI a Kiro CLI no es cosmético. Es una señal clara de hacia dónde va AWS con sus herramientas de desarrollo: agentes con contexto persistente, conectados a tus herramientas vía MCP, que entienden las convenciones de tu equipo vía steering files, y que pueden actuar — no solo responder.

Las capacidades clave que ganamos:

  • kiro-cli chat — Chat agéntico con capacidad de leer/escribir archivos y ejecutar comandos
  • kiro-cli translate — Traduce lenguaje natural a bash
  • kiro-cli inline — Sugerencias inteligentes mientras escribes
  • MCP Integration — Conecta herramientas externas (CloudWatch, MSK, OpenSearch, etc.)
  • Agent Steering — Dale contexto persistente a Kiro con las prácticas y convenciones de tu equipo
  • Custom Agents — Crea agentes especializados para tus workflows
  • Smart Hooks — Automatización pre/post comandos
  • Headless Mode — Integración con CI/CD vía API keys

Y un punto importante: Spec-Driven Development es exclusivo del Kiro IDE. Si quieres el workflow completo de specs (requirements → design → tasks → implementación), necesitas el IDE. La CLI es para chat, automatización, MCP, y operaciones desde la terminal. Ambos comparten steering files, así que tu contexto de proyecto funciona en los dos.

Mi recomendación: instala Kiro CLI, crea un steering file para tu proyecto más activo, conecta un servidor MCP relevante para tu stack, y experimenta. La curva de aprendizaje es corta y el salto de productividad es real.

Yo soy Carlos Cortez y esto es Breaking the Cloud — nos vemos pronto.

Sígueme en:

Meta GEM 推薦基石模型深剖:大廠限定的工程地獄與落地取捨

Meta GEM 推薦基石模型深剖:大廠限定的工程地獄與落地取捨

Meta 最近揭露了其廣告推薦中央大腦 GEM(Generative Ads Recommendation Model) 的技術細節。公關數據非常漂亮:Instagram 廣告轉換率提升 5%,Facebook Feed 提升 3%,訓練效率是傳統蒸餾的 2 倍。

但站在做落地判斷的工程師視角,這是一篇典型的「大廠資源秀肌肉」報告。它堆砌了萬卡 GPU、自研 NCCLX 通訊與 Jagged Tensor 算子。以下我們直接扒開架構,評估其真正的工程代價與落地可行性。

一、 架構設計:解決稀疏性,但代價是推理延遲(Inference Latency)

推薦系統的核心痛點在於特徵空間極度稀疏(Sparse)與行為序列長度不一。GEM 採用了三個關鍵架構來應對:

  1. Wukong(悟空)非序列特徵交叉:
    利用可堆疊的因子分解機(Factorization Machines)配合 Cross-layer Attention 連接。

    • 取捨評估:這能強迫模型學到深層的特徵互動,但多層注意力機制在線上預估(Online Serving)時會帶來災難性的推理延遲(Inference Latency)。
  2. InterFormer 序列與特徵交替學習:
    傳統方法會把用戶歷史序列先壓縮成一個 Embedding 向量再傳給下游,這會造成行為訊號嚴重流失。InterFormer 選擇交替進行序列學習與跨特徵交互。

    • 取捨評估:保留了完整的行為路徑,代價是記憶體頻寬與 Embedding 儲存開銷暴增。
  3. 金字塔平行結構(Pyramid-Parallel Structure):
    在處理數千長度的用戶行為序列時,透過堆疊平行模組來降低儲存開銷。

    • 取捨評估:這能把複雜度壓下來,但越往金字塔上方傳遞,特徵細節的損耗就越大。

💡 落地判斷:

Meta 敢用 Wukong 和 InterFormer,是因為他們把 GEM 定位為離線基石模型(FM),不直接線上 Serving,而是透過知識蒸餾把參數傳給線下的百個小模型(VM – Vertical Models)。如果你的團隊沒有這套 FM-VM 的離線-線上蒸餾架構,直接拿 Wukong / InterFormer 跑線上即時推薦,無異於線上自殺。

二、 知識傳遞(Knowledge Transfer):解決監督過期(Stale Supervision)的妙招

GEM 大模型線下訓練有時間差,而線上 VM 需要應對實時變化的用戶行為。這會導致「監督過期」(Stale Supervision),即 FM 傳給 VM 的知識可能已經過時。

Meta 採用了三個 Post-training 技巧(效率宣稱為傳統蒸餾的 2 倍):

+------------------------------------------+
|      GEM Foundation Model (Teacher)      |
+------------------------------------------+
                     |
                     v
+------------------------------------------+
|       Student Adapter (即時修正)          | <--- 接入最新 Label 修正偏差
+------------------------------------------+
                     |
      +--------------+--------------+
      | (知識蒸餾)   | (特徵表示)   | (參數共享)
      v              v              v
+------------------------------------------+
|          Vertical Models (VMs)           |
+------------------------------------------+
  • Student Adapter(學生適配器):
    在蒸餾過程中加入輕量級 Adapter,用最新產生的 Ground-truth 標籤實時修正 Teacher 的預估值,拉回時間差造成的預估偏差。
  • 特徵表示學習(Representation Learning):
    不只蒸餾機率,更把 Teacher 與 Student 的特徵語意對齊,完全不增加線上推理延遲。
  • 參數共享(Parameter Sharing):
    讓小模型直接複用大模型的特定參數,節省運算成本。

💡 落地判斷:

Student Adapter 是整篇報告中最具實用價值的工程細節。任何做離線-線上模型蒸餾的團隊都應該抄這招。它唯一的代價在於你需要一套極度穩定、低延遲的即時標籤回傳(Real-time Labeling Pipeline)。

三、 訓練基礎設施:重度定製的軟硬體協同(一般團隊玩不起)

Meta 宣稱在 GPU 數量擴大 16 倍的情況下,跑出 23 倍的有效訓練 FLOPS,MFU(模型 FLOPS 利用率)提升 1.43 倍。

不要只看這張成績單,背後是重度的工程定製:

  1. 2D 稀疏平行(2D Sparse Parallelism):
    推薦模型跟 LLM 不同,Dense 部分(Attention/MLP)用 HSDP(混合分片分散式平行),而 Sparse 部分(Embedding Table)則是用資料+模型雙重平行。這對節點間的通訊頻寬要求極端苛刻。
  2. Jagged Tensor 自研算子:
    用戶的序列長度通常是參差不齊的(Jagged)。傳統做法是 Padding 補零,但這在 GPU 運算上是巨大的浪費。Meta 為此編寫了客製化 GPU Kernel,支援不規則序列的算子融合(Computation Fusion)。
  3. NCCLX 通訊庫:
    這是 Meta 對 NCCL 的自研分支,核心優化是讓通訊集合不佔用 GPU 的 SM 資源,實現計算與通訊的完全重疊(Overlap)。

💡 落地判斷:

這些優化不是在演算法層面,而是在 CUDA 算子和網絡拓撲級別的重度改造。非巨頭企業根本沒有足夠的編譯工程師與硬體專家來開發和維護這套客製化工具鏈。

四、 YangGF 的落地判斷 (Landing Assessment)

維度 評估結論
已發布 (Released) 是。論文與架構細節已揭露。
可用性 (Available) 否。外部開發者無開源模型可用。
可商用性 (Commercially Viable) 極低(僅限廣告超大廠)。只有在廣告變現流水足以覆蓋萬卡 GPU 維護與研發成本的前提下,ROI 才能轉正。
工程瓶頸 1. 訓練通訊頻寬:Sparse 部分對網路 I/O 要求高。
2. 維護代價:FM-VM 的雙層蒸餾 pipeline 極易因標籤異常而崩潰。
3. 客製化工具鏈:Jagged Tensor 算子與 NCCLX 對基礎設施工程能力要求過高。

🛠️ 給架構師的落地建議:

如果你的團隊不是位列一線的流量巨頭,千萬不要盲目跟風去架構一個千億參數的推薦基礎大模型。
我們應該把錢花在刀口上,吸收 GEM 的實用精髓:

  1. 抄 Student Adapter 的思路:在你的蒸餾 Pipeline 中加入時效偏差修正,低成本解決離線模型時效性差的硬傷。
  2. 參考 Jagged Tensor 算子融合:最佳化你的長行為序列特徵在 GPU 上的運算效率,避免 padding 浪費算力。

🤔 讀者交流時間

各位在實際推薦系統的落地中,如何處理離線大模型(Teacher)與線上小模型(Student)之間的特徵與標籤時效性(Staleness)偏差?你們有嘗試過類似 Student Adapter 的微調機制嗎?

歡迎在下方留言,我們一起探討。