Foundation of Reinforcement learning(IV)

Introduction

In the previous posts, we have introduced the MDP and its solution. But in practice, we often do not have the simulation of the environment, which means we cannot directly apply our knowledge of MDP to solve the problem. There is indeed a method to simulate the environment, which is called model-based Reinforcement learning. However, in this post, we will focus on the model-free Reinforcement learning, which does not require the simulation of the environment and the construction of MDPs.

Estimating Value Functions

In mode-based RL, value functions can be computed by DP methods as follows:

However, in model-free RL, we cannot directly access the and , but we have some ways to estimate the value function from episodes of experience.

Why we estimate the value function?
Because we can use the value function to derive the optimal policy, which is our ultimate goal. Besides value function can help us to reuse historical experience to make better decisions in the future, which is the essence of Reinforcement learning.

Here is a graph to introduce some methods to estimate the value function:

value estimation(Slide credit: David Silver)

Monte Carlo methods

Target: Learn from episodes of experience.

Review: accumulate reward function:

Review: value function is the expected return:
The Monte Carlo method use empirical mean cumulative reward instead of expected return to estimate the value function.

First-visit Monte Carlo method

The first-visit Monte Carlo method estimates the value function by averaging the returns following the first time a state is visited in an episode. The algorithm is as follows:

  1. Initialization:
    • For any ,, .
    • For any ,.
  2. Loop for each episode:
    • Generate an episode following policy : .
    • For t = T-1, T-2, …, 0:
      • If is the first time in the episode:
        • Append to .
        • .

The reason why we call it ‘first-visit’ is that we only update the value function for the first time we visit a state in an episode. Thus we can avoid the bias caused by multiple visits to the same state in an episode. However, this method may have high variance because it only uses one return for each state in an episode.

Incremental Monte Carlo method

The first-visit Monte Carlo method takes a lot of memory to store the returns for each state, which is not efficient. The incremental Monte Carlo method uses an incremental update rule to estimate the value function without storing all the returns. The algorithm is as follows:

  1. Initialization:
    • For any ,, , .
  2. Loop for each episode:
    • Generate an episode following policy : .
    • For t = T-1, T-2, …, 0:
      • If is the first time in the episode:
        • .

Interesting, online softmax also takes the same update rule as the incremental Monte Carlo method. Great job.

Besides, incremental MC provides more design space for us to tackle some problems in practice. For example, we can use a constant step size instead of to update the value function, which is called constant step size MC method. It is useful when the environment is non-stationary, which means the reward function and transition probability may change over time. In this case, we want to give more weight to recent returns than old returns, which can be achieved by using a constant step size :

Some properties of Monte Carlo methods

  1. Monte Carlo methods are model-free, which means they do not require the knowledge of the environment’s dynamics (transition probabilities and reward function).
  2. Monte Carlo methods take the simpliest approach to estimate the value function, which is to average the returns following the policy. However, this method may have high variance because it only uses one return for each state in an episode.
  3. One key to note is that Monte Carlo methods can only be applied to finite MDPs, which means the state space and action space must be finite.

Importance sampling

Let’s try to estimate a custom distribution ‘s expectation.
Then we reassign the importance sampling weight , we can rewrite the above equation as:

Off-policy Monte Carlo methods via Importance Sampling

We can use the cumulative reward function of policy to justify policy , and then weight the cumulative reward function by the importance ratio between and to estimate the value function of policy . The algorithm is as follows:

Every episode would be mutified by the importance sampling ratio:

So we then update the value function by:

Sample by importance sampling will significantly increase the variance of the return, which is because the importance sampling ratio can be very large when and are very different.

Temporal-Difference Learning

Temporal-Difference (TD) is a method combining the MC method and DP method, which name comes from the fact that it uses the diff of estimated value function at two consecutive time steps to update the value function. There are two key ideas in TD learning: TD error and TD target.

For state value funtion , after a transition from state to state with reward , the TD error is defined as:
The TD target is defined as:

As for the TD in Bellman expectation equation, the TD error is used in estimating the expect part.

Some details of TD learning

The simpliest TD learning algorithm is called TD(0), which updates the value function by the TD error at each time step. The key equation of TD(0) is as follows:

Why we update like this?
The Bellman expectation equation is rewritten as:


That’s all. We want to make the TD error as small as possible, which means we want to make the estimated value function as close as possible to the true value function. Thus, we can use the TD error to update the value function.

The TD method introduce the bootstrapping idea, which means we use the estimated value function to update the value function. This is different from the MC method, which uses the actual return to update the value function. The bootstrapping idea can significantly reduce the variance of the return, but it may introduce bias because we are using an estimated value function to update the value function.

Contrast between TD and MC methods

They have the same goal: Learn the value function from episodes of experience. However, they have different approaches to achieve this goal. The MC method uses the actual return to update the value function, which can have high variance but no bias. The TD method uses the estimated value function to update the value function, which can have low variance but may introduce bias.

TD method MC method
update value function like update value function like

The object of TD is , which is called TD target, while the object of MC is , which is the actual return. The TD method’s error is called TD error, which is defined as , while the MC method’s error is defined as .

The strengths and limitations of TD learning and MC learning

TD method can learn until the end of an episode:

  • After each step in an episode, TD method can update the value function use the former value function, which means it can learn until the end of an episode. However, MC method can only update the value function after the end of an episode, which means it cannot learn until the end of an episode.
  • TD method can learn from incomplete episodes, which means it can learn from episodes that are not terminated. However, MC method can only learn from complete episodes, which means it cannot learn from episodes that are not terminated.

Tradeoff between bias and variance

Estimator Bias Variance
MC Unbiased: Higher
TD (real) Unbiased: Lower
TD (actual) Biased: Lower

Note: The real TD target uses the true , which is unknown in practice. The actual TD target uses the current estimate , introducing bias. Despite the bias, TD typically has lower variance than MC because it bootstraps from a single step rather than a full trajectory.

Multi-step TD learning

The TD(0) method only uses the immediate reward and the estimated value of the next state to update the value function, which may not be sufficient to capture the long-term dependencies in the environment. The multi-step TD learning method uses the rewards and estimated values of multiple future states to update the value function, which can better capture the long-term dependencies in the environment. We will introduce it by leading into n-step cumulate reward function and n-step TD target.

N-step cumulate reward function

Consider the following n-step cumulate reward function:
It seems make sense to use the n-step cumulate reward function to update the value function, which is called n-step TD learning. The key equation of n-step TD learning is as follows:

N-step mean cumulate reward function

Can we take up the information of different n-step cumulate reward function to update the value function? The answer is yes.
We can use a weighted average of different n-step cumulate reward functions to update the value function, which is called n-step mean TD learning. The key weight figure of weighted average is as follows:

lambda weight

So the n-step mean cumulate reward function is defined as:
Then we can update the value function by:

This is called TD() method, which is a generalization of TD(0) and MC methods. When , TD() reduces to TD(0) method, and when , TD() reduces to MC method. Thus, by adjusting the value of , we can control the bias-variance tradeoff in the estimation of the value function.

Conclusion about TD(λ) method

  • Unless the is 0, TD() mothod is unbiased, because it’s a weighted average of unbiased n-step TD targets.

  • The variance of TD() method is lower than that of MC method, because it uses bootstrapping to update the value function, which can reduce the variance of the return. However, the variance of TD() method is higher than that of TD(0) method, because it uses more rewards and estimated values to update the value function, which can increase the variance of the return.

  • Empirically is not quite commom because fast credit assignment for a given action is preferred. So MC or TD(0) is more commonly used in practice. However, TD() method can be useful when we want to balance the bias-variance tradeoff in the estimation of the value function, which can be achieved by adjusting the value of .

So TD() use as variable while n-step TD use as variable. TD() is a generalization of n-step TD, which can be seen as a weighted average of infin-step TD targets. By adjusting the value of , we can control the bias-variance tradeoff in the estimation of the value function, which can be useful in practice when we want to balance the bias and variance in the estimation of the value function.

Conclusion

In this post, we have introduced the model-free Reinforcement learning, which does not require the simulation of the environment and the construction of MDPs. We have introduced two methods to estimate the value function from episodes of experience: Monte Carlo methods and Temporal-Difference learning. We have also introduced the n-step TD learning method, which uses the rewards and estimated values of multiple future states to update the value function, which can better capture the long-term dependencies in the environment. Finally, we have discussed the bias-variance tradeoff in the estimation of the value function, which can be controlled by adjusting the value of in TD() method.

Foundation of Reinforcement learning(III)

Introduction

In the previous post, we have introduced the Bellman equation and the linear programming formulation for MDP. In this post, we will discuss the model-based Reinforcement learning, which is a method to solve the MDP when we do not have the model of the environment.

The Settings of RL

Typically, RL is framed as MDP, exploring the enviroment and learning the optimal policy.
Generally, we can only observe the episodes and usually, we do not have the model of the environment.

So we need to introduce the model into our RL project. Model-based RL actually is a method to solve the MDP.

Dynamic Programming Based RL

Dynamic Programming for finite MDP

Our objective function is simple, just the expected return, which is defined as:

In the first episode of the series, we introduced Backward induction, which we can start from the last step and then recursively solve the problem. However, this method is not efficient for large state space, and it requires the state transition.

But meanwhile, we can also use the Bellman equation of value function to tackle the problem:

Optimal Value Function

For a state , we can define the optimal value function as the maximum value function over all policies:
So the optimal value function is as follows:

So the best policy can be derived from the optimal value function as:

for any state and policy , there is:

Obviously, the value function relates to the policy, so we can iterate the optimal value function and the optimal policy until convergence. They are called Value Iteration and Policy Iteration respectively.

Value Iteration

For an MDP which is finite in both state and action space, we can use the value iteration to solve the problem. The value iteration is as follows:

  1. Initialize for all
  2. For each state , update the value function as:
  3. Repeat step 2 until convergence.

NOTE: There isn’t any specific order to update the value function, we can update the value function in any order. But the convergence rate may be different.

Sync & Async Value Iteration

Sync value iteration need to store two copies of value funtion:

  1. For any state , we update the value function as:
  2. After updating all states, we copy the new value function to the old value function:

Async value iteration only need to store one copy of value function:

Policy Iteration

The assumption of MDP is the same as the value iteration, which is finite in both state and action space. The policy iteration is as follows:

  1. Randomly initialize a policy and a value function for all
  2. Repeat the following steps until convergence:
  3. Policy Evaluation: For each state , update the value function as:
  4. Policy Improvement: For each state , update the policy as:

Obviously, the Policy Iteration will be more expensive than the Value Iteration, since it needs to evaluate the policy in each iteration. However, the Policy Iteration can converge faster than the Value Iteration, since it can update the policy in each iteration.

Let’s contrast the two methods:

Method Value Iteration Policy Iteration
Update Value function Policy and value function
uses Bellman optimality equation Bellman expectation equation

NOTE:

  1. Value iteration is a greedy method, we always use the best.
  2. Update the value function by Bellman equation in Policy Iteration is expensive.
  3. For smaller space MDP, Policy Iteration is faster than Value Iteration, but for larger space MDP, Value Iteration is faster than Policy Iteration.
  4. If there isn’t any state transition circle, the value iteration is better.

Bellman operators

In fact, we have introduced the Bellman operators in the previous post, but we haven’t discussed it in detail.

Why Policy Iteration and Value Iteration can converge to the optimal value function? The key is that Bellman operators are contraction mappings.

Bellman operator is the collection of below functions:

  1. Bellman expectation operator, usually denoted as , which is defined as:

  2. Bellman optimality operator, usually denoted as or , which is defined as:

They can be used on the state value function and action value function:

  • expectation operator is used in the policy iteration, used for computing
    the value function of a given policy, while is the inner loop of the policy iteration.
  • optimality operator is used in the value iteration, used for computing the optimal value function, while is the main loop of the value iteration.

Both the Bellman expectation operator and the Bellman optimality operator can be defined on the action value function and the state value function:

  1. Bellman expectation operator on V-function:

  1. Bellman optimality operator on V-function:

  1. Bellman expectation operator on Q-function:

  1. Bellman optimality operator on Q-function:

Due to the contraction property of the Bellman operators, we can guarantee the convergence of the value iteration and policy iteration to the optimal value function.

Model RL

In the above sections, our objective environment is a known MDP, all our methods are based on the assumption that we have the model of the environment, which is the transition probability and the reward function. However, in many real-world scenarios, we do not have the model of the environment, so we need to learn the model from the data.

There are two basic thoughts to learn the model of the environment:

  1. learn the state transition probability:

    where is the number of times we have observed the transition from state to state when taking action , and is the number of times we have observed taking action in state .

  2. learn the reward function :

    where is the number of times we have observed taking action in state , and is the average reward we have observed when taking action in state .

The simple simulate algorithm is as follows:

  1. randomly initialize a policy
  2. repeat the following steps until convergence:
  3. collect data by executing the policy in the environment, and store the transition data in a replay buffer.
  4. learn the model of the environment from the replay buffer, which includes learning the state transition probability and the reward function.
  5. solve the MDP with the learned model to get the optimal policy .

Other method to solve this is not learning the MDP, instead we learn the value function directly from the data, which is called model-free RL, we will discuss it in the next post.

Conclusion

In this post, we have introduced the model-based Reinforcement learning, which is a method to solve the MDP when we do not have the model of the environment. We have discussed the value iteration and policy iteration, which are two basic methods to solve the MDP. We have also introduced the Bellman operators, which are the key to guarantee the convergence of the value iteration and policy iteration. Finally, we have introduced the simple simulate algorithm, which is a method to learn the model of the environment and solve the MDP with the learned model. In the next post, we will discuss the model-free Reinforcement learning, which is a method to learn the value function directly from the data without learning the model of the environment.

Foundation of Reinforcement learning(II)

Introduction

Given the former post where we have introduced the MDP and some basic properties, we are now ready to discuss the MDP-based Reinforcement learning. But first, we need to introduce the solution of MDP.

Bellman Equation

If we have learned the previous post, we will know that there are two types of value function, state value function and action value function. Their mathematical definitions are as follows:

Instinctively, the state value function is the expected return when we start from state and follow policy . Similarly, the action value function is defined as:

Here, it represents the expected return when we start from state , take action , and then follow policy thereafter.

On the other hand, we have a accumulate reward function, which is defined as:
It can be recursively defined as:

So, we can rewrite the state value function as:
Above is the Bellman expectation equation for the state value function. Now, our question is to choose the best policy to maximize the value function. We can define the optimal state value function as:

Due to the Principle of Optimality: Each stage of an optimal policy must be optimal for the remaining stages, we can derive the Bellman optimality equation for the state value function as:

Above is the Bellman optimality equation for the state value function.

Linear Programming for MDP

We have a key observation that the Bellman optimality equation can be rewritten as a linear programming problem. The linear programming formulation for MDP is as follows:

Proof:
The first part is to show that the optimal value function is a feasible solution to the above linear programming problem. We can see that for any state and action , we have:
Thus, satisfies the constraints of the linear programming problem.
The second part is to show that any feasible solution satisfying the constraints must be greater than or equal to .
Given that the optimal policy choose one action for each state , LP constraints imply that for any state :
Let’s write them in matrix form:
while the is the reward vector under policy , and is the transition matrix under policy . We can rearrange the above inequality as:
Since , we can conclude that is invertible, and we can get its inverse as:
Obviously, the above inverse is a non-negative matrix. Thus, we can multiply both sides of the inequality by to get:
Since , we can conclude that .
So, we have shown that any feasible solution is greater than or equal to , and the optimal value function is a feasible solution. Thus, the optimal solution to the linear programming problem is .

Given we have the , we can easily derive the optimal policy as:

Here I asked claude to give me a simple explanation of the equivalence between this greedy like policy decision and the optimal policy. The formal proof may be need to use the fixed point theorem, but it is beyond the scope of this post. We just need to remember that the optimal policy can be derived from the optimal value function by choosing the action that maximizes the expected return.

The Dual Linear Programming for MDP

The dual linear programming formulation for MDP is as follows:

If the initial state distribution for all , then let
, the target function means the expected accumulated reward represented by the occupancy measure, and the constraints means the flow conservation constraints.

Assume that the optimal solution is , we can derive the optimal policy from Theorem 2 as:

Comparison between the Primal and Dual Linear Programming for MDP

Dimension Primal LP Dual LP
variable state value function occupancy measure
objective minimize maximize
constraints Bellman optimality constraints flow conservation constraints
explanation state value action frequency

Summary

At the beginning of this post, I tried to introduce the MDP-based Reinforcement learning, but I found that the solution of MDP takes a lot of space, so I just introduce the Bellman equation and the linear programming formulation for MDP. In the next post, I will introduce the value iteration and policy iteration algorithms for solving MDP, which are based on the Bellman equation.

Foundation of Reinforcement learning(I)

The category of decision making problem

dimension single step multi step
one person optimization problem RL, to the best situation
multi person static game dynamic game, MARL.etc

Dynamic programming

Dynamic program is used to solve the Sequential decision making problem, feature of this problem is that it’s decision making process is sequential, and the decision at one step will affect the next step, and the reward is received at the end of decision making process, not at each step.

For an example, given a maze like problem below, the agent need to find a way from Position A to Position B, and the time of each way is different. Agent need to find the way with the least time. A simple way to solve this is to list all the possible paths, but if there is a circle, if the map is large, this will be unfeasible.

A better way to solve this is Backward induction, we start from the end point, and for evey point we calculate the time to reach the end point, then we regart the selected point as the new end point, and repeat this process until we reach the start point. This is a dynamic programming method, and it can solve the problem in polynomial time. But due to we need find a backward path, this method is only suitable for DAG, if there is a circle, this method will fail.

maze

The example is just a introduction, we can summarize the features of dynamic programming as follows:

  • it start from the end, and caculate the best action for each state.
  • it traverse all the states, and for each state, it calculate the best action, and the value of this state.
  • it need to define the state, path(state transition), time(online reward)

So it lead to the Principle of Optimality:

An optimal policy has the property that whatever the initial state and initial decision are, the remaining decisions must constitute an optimal policy with regard to the state resulting from the first decision.

Markov Decision Process

Stochastic Process

A stochastic process is a collection of random variables, which can be used to describe the evolution of a system over time. It’s mathematical definition is as follows:
This means that the probability of the next state depends on the current state and all the previous states .

Markov Process

Compared to stochastic process, Markov process has a stronger assumption, which is “the future is independent of the past given the present”. Mathematically, it’s definition is as follows:
This means that the probability of the next state only depends on the current state , and is independent of all the previous states .

Trying to understand it’s property is that the current state contains all the information about the past, so we can make decision based on the current state without worrying about the past.

Markov Decision Process

Markov Decision Process (MDP) provides a mathematical framework for modeling decision making in situations where the outcome is partly random, partly under the control of a decision maker. An MDP is defined by the following components:

  • State space (S): A set of all possible states in the environment.
  • Action space (A): A set of all possible actions that the agent can take
  • Transition function (P): A function that defines the probability of transitioning from one state to another given a specific action. It is denoted as , which represents the probability of transitioning to state from state after taking action .
  • Reward function (R): A function that defines the reward received after transitioning from one state to another given a specific action. It is denoted as , which represents the reward received after taking action in state . Sometimes only relates to the State.
  • Discount factor (γ): A factor that determines the importance of future rewards. It is a value between 0 and 1, where a value closer to 0 makes the agent prioritize immediate rewards, while a value closer to 1 makes the agent consider future rewards more heavily.

The dynamic feature of MDP

The whole process of MDP is dynamic as follows:

  1. The agent observes the current state .
  2. The agent selects an action based on its policy , which is a mapping from states to actions.
  3. The agent gets a reward .
  4. The MDP transitions to a new state according to the transition function .

The total reward that the agent receives over time is often defined as the discounted sum of rewards:

Markov Policy

In the context of MDP, a policy is a function that depends on the history:

But a Markov policy is a special type of policy that only depends on the current state:


In the RL setting, we usually assume that the policy is a Markov policy. Why?

The MDP has Markov property, which means the future is independent of the past given the present, so there is no special information in the history that can help us make better decision, so we can just use the current state to make decision.More informally, for any policy relying on the history, we can find a Markov policy that at least performs as well as it does, so we can just focus on Markov policy without loss of generality.proof(the 26th and 27th slides of the lecture)


The category of MDP Policy

At the time demension, we can categorize the policy into two types:

  • Stationary policy: A policy that does not change over time. It is defined as , which means the action taken in state is the same at any time step.
  • Non-stationary policy: A policy that can change over time. It is defined as , which means the action taken in state can be different at different time steps.

At the probability distribution demension, we can categorize the policy into two types:

  • Deterministic policy: A policy that always selects the same action for a given state. It is defined as , which means the action taken in state is always .
  • Stochastic policy: A policy that selects actions according to a probability distribution. It is defined as , which means the action taken in state is selected according to the probability

In the RL setting, we usually assume that the policy is a stationary policy. Why?
Typically, we consider the infinite horizon setting. There is also a proof that for any non-stationary policy, we can find a stationary policy that at least performs as well as it does, so we can just focus on stationary policy without loss of generality. proof(the 29th and 32th slides of the lecture)


The best policy for MDP

There is a theorem:

In a situation that the discount factor , while the state and action space are finite and the horizon is infinite, there exists a deterministic
and stationary policy that is optimal, which means for any policy , we have .

Proof: Puterman, Martin L. Markov decision processes: discrete stochastic dynamic programming. John Wiley & Sons, 2014.

The goal of MDP

Our goal is to choose the action to maximize the expected reward, which is defined as follows:

So we can define the value function for a policy as follows:
This means the expected reward that the agent can get starting from state and following policy .

Occupancy Measure

In MDP context, the occupancy measure is a way to represent the discounted state-action expectation under a policy , also known as state-action visitation distribution. It is defined as follows:

while the means the state transition, which is defined as follows:

On the other hand, the state occupancy measure is defined as follows:

How to compute the occupancy measure?

State occupancy measure

We assume that the initial state distribution is , then we can compute the state occupancy measure as follows:

then we can solve the fomula:

State-action occupancy measure

We can compute the state-action occupancy measure as follows:

Pay attention that the whole process is flow conservation. Because the state-action occupancy measure is the expected discounted number of times that the agent takes action in state , so the total flow into state must equal the total flow out of state . This is why we have the flow conservation constraint in the computation of occupancy measure.

Some Properties of Occupancy Measure

Obviously, from the definition of the measures:

We have two important theorems about the occupancy measure:

  • Theorem 1: For two policies and interacting with the same dynamic environment, if , then .
  • Theorem 2: Given a Occupancy measure , the only policy that can generate this occupancy measure is .

Accumulated reward for a policy

As we have defined the occupancy measure, we can compute the accumulated reward for a policy as follows:

Value function and Q function

The value function is used to evaluate a state or a state-action pair, given a policy .

The state value function is usually know as value function, which is defined as follows:

The state-action value function is usually know as Q function, which is defined as follows:


Obviously, we have the relationship between the value function and the Q function:
And we can also compute the value function and Q function using the occupancy measure as follows:


Summary

  • MDP provides us a simple but powerful mathematical framework to model the sequential decision making problem.

  • The five-tuple of MDP is defined as , which represents the state space, action space, transition function, reward function and discount factor respectively.

  • Markov poverty is the key assumption of MDP, which means the future is independent of the past given the present.

  • Policy is the function to choose the action, usually is a conditional probability distribution over actions given states, and we usually assume that the policy is a stationary policy.

  • Occupancy measure is a way to represent the discounted state-action expectation under a policy, which can be used to compute the accumulated reward for a policy.

  • State value function and state-action value function are used to evaluate a state or a state-action pair, given a policy, and they can be computed using the occupancy measure.

nanoPD:一个 LLM P/D 分离推理引擎的实现笔记

这个项目的起因是读 vllm, DistServe 和 Mooncake 的时候有些地方没有完全想清楚,觉得与其在论文层面反复打转,不如自己动手实现一遍,于是花了一段时间和 claude 大人一起从零写了一个支持 Prefill/Decode 分离调度的推理引擎,覆盖了从 CUDA 内核到自适应路由器的完整栈,代码大约 2000 行 Python 加 400 行 CUDA C++,每个模块有单独的文档,也顺手做了中英双语版。(菜菜勿喷呜呜)

背景和动机

LLM 推理的两个阶段在计算特性上的差异非常显著, prefill 是一次性处理整个 prompt 的过程,本质上是大规模的 GEMM ,算力密集, GPU 的计算单元在这个阶段是满载的;而 decode 每步只生成一个 token ,每次前向传播只有一个(或很少几个)新 token 需要计算,但需要从显存里读取所有历史 token 的 KV cache ,是典型的 memory bound 操作, GPU 的计算单元大部分时间在等数据,实际上 decode 阶段的算术强度非常低,主要的开销是 HBM 的读取带宽。

这两种操作对 GPU 资源的需求模式截然不同,把它们放在同一张卡上并发运行时会产生 SM 资源的竞争, prefill 的矩阵乘法会占用大量 SM ,导致同时在跑的 decode 请求的 attention 计算被推迟,表现出来就是 decode 的延迟在有 prefill 并发时会显著上升,这种干扰在高并发场景下尤其明显,也是 vLLM 等系统在负载较高时尾延迟劣化的一个重要原因。

P/D 分离( Disaggregated Serving )的思路是把 prefill 和 decode 分配到专用的 GPU 上,让两个阶段互不干扰,这个方向在工业界和学术界都有比较多的工作, DistServe 比较系统地分析了分离的收益, Mooncake 则是
月之暗面在生产系统中实践分离调度的工程经验,两篇文章读起来都很有意思,但读完之后我对一些具体的设计决策仍然有疑问,比如路由策略在不同硬件上的表现差异有多大,代价模型里的参数对结论的敏感性如何,这些问题通过实现一遍会有更直接的感受。

实现栈,从底到上

CUDA 内核部分手写了 paged attention kernel 和 KV store ops ,主要是想理解非连续内存块上的 attention 是怎么做的,传统的 attention 假设 KV cache 存储在连续内存里,但 paged KV cache 把显存切成固定大小的物理块,序列的 KV 数据分散在这些块中, attention 计算需要根据 blocktable 做间接寻址,实现上需要在 CUDA kernel 里根据 token 的位置先找到对应的物理块再读取数据,这个 gather 操作相比连续 KV cache 有额外的开销,但换来的是显存利用率的显著提升,因为不再需要为每条序列预先分配最大长度的连续显存,这个 tradeoff 在长序列和高并发场景下非常值得。内核的实现参考了 vLLM 的设计,但为了保持简单没有做 Flash Attention 那样的 tiling 优化,所以在长序列上性能差很多,这部分如果要真正优化的话工作量还是比较大的。( next work 预定了说是)

块管理器以 block 为粒度管理显存的分配和释放,逻辑上类似操作系统的虚拟内存管理,每个物理块有引用计数,引用计数降为零时才真正释放,支持 Copy-on-Write fork ,这个特性在 beam search 或者需要复制序列状态的场景下有用, fork 的时候共享物理块,只有在某条路径需要写入新 token 时才触发实际的物理块复制,避免了不必要的显存拷贝。

推理引擎实现了 chunked prefill ,长 prompt 会被切成固定大小的 chunk 和当前正在 decode 的请求交错执行,而不是一次性把整个 prompt 打进去阻塞所有 decode 请求,这个设计的好处是降低了 prefill 对 decode 的干扰,代价是单个请求的 prefill 总时间会因为被切分而略有增加,调度器维护 waiting 、 prefilling 、 running 三个队列,每一步决定哪些请求进入 prefill 、哪些进行 decode 、 chunk 大小是多少,这些调度决策对系统的整体延迟和吞吐影响很大,实现上采用了比较简单的启发式策略,没有做复杂的动态调整。

Worker 层分三类,

  • CollocatedWorker 在单卡上同时做 prefill 和 decode ,内部复用了推理引擎的调度器;
  • PrefillWorker 专门处理 prefill ,完成后把生成的 KV cache 从 GPU 显存提取到 pinned memory buffer (为什么我的服务器连 PCIe 都没有!!!),准备传输;
  • DecodeWorker 接收传输过来的 KV cache ,加载到自己的显存后把对应的序列加入 decode 队列。
    三类 Worker 可以在不同 GPU 上并发运行,由上层的 CentralScheduler 协调, CentralScheduler 把 collocated 和 disaggregated 两条 pipeline 跑在独立的线程上,每个 step 并发执行,然后汇总结果。

KV 传输部分用了独立的 transfer stream ,目标是和 compute stream 尽量 overlap ,减少等待时间,代码里用 torch.cuda. Event 来同步两个 stream 之间的依赖,实现上比较简单,没有做精细的 pipeline 重叠,实际测下来 overlap 的效果取决于传输数据量和计算量的比例,在小 batch 或短序列的时候效果不太明显。同时会自动检测当前硬件是否支持 P2P 直传,通过 torch 的 _check_p2p 接口查询,不支持的话 fallback 到 pinned memory relay ,也就是先把数据从 GPU 拷到 CPU 的 pinned memory ,再从 pinned memory 拷到目标 GPU ,这个路径的带宽会受限于 PCIe ,在没有 NVLink 的多卡环境下(比如 8 张 4090 通过 PCIe 互联)这个开销是比较显著的,实测大约 12.9 GB/s ,而有 NVLink 的 H20 可以达到约 392 GB/s ,差了将近 30 倍,这个差距直接决定了路由判断在两种硬件上的结论会有多大的不同。

代价模型和路由

为了决定每个请求走合并路径还是分离路径,我实现了一个解析式代价模型,思路是先在真实设备上跑 micro-benchmark 测四个参数, prefill 速度α( ms/token )、 decode 单步延迟 β( ms )、 prefill 对 decode 的干扰系数 γ( ms/token )、以及 GPU 间传输带宽 bw ( GB/s ),然后用这四个参数建立两条路径的延迟估算公式,每个请求来了之后实时计算预估延迟并选更小的那条,所有参数都来自实测,没有用论文里的理论值,因为不同的硬件和软件环境下这些数字差异很大,直接用实测值比从理论推导更可靠。

profiling 的过程大概是: prefill latency 用不同长度的 prompt 各跑若干次取中位数,用线性回归拟合得到 α; decode latency 在不同的 KV 长度和 batch size 下各测一遍,用来拟合 β 和 batch_thresh ( decode 从内存带宽瓶颈切换到算力瓶颈的拐点); interference 通过对比纯 decode 和混合 prefill+decode 下 decode 延迟的差值来测量,用线性回归拟合得到 γ; P2P 带宽直接测一次大块数据传输的时间来估算。

路由判断最后可以化简成比较两个都正比于 prompt 长度 L 的量,分离路径相比合并路径的额外代价是传输 KV cache 的时间,大约是 transfer_rate× L ,合并路径相比分离路径的额外代价是 prefill 对并发 decode 的干扰,大约是 γ × L × (system_load / batch_thresh),分离更划算的条件可以化简为 γ / transfer_rate > batch_thresh / system_load ,其中γ / transfer_rate 是一个只取决于硬件的比值,反映了”干扰有多贵”相对于”传输有多贵”的比例,而 batch_thresh / system_load 则反映了当前系统的负载程度。

在 RTX 4090 上实测,γ / transfer_rate ≈ 7.6 ,代入 batch_thresh = 16 可以得到 system_load ≥ 约 2.1 时分离就开始划算,也就是只要有两到三个并发请求在跑,分离路径在延迟上就已经比合并路径更好了;而在 H20 上这个比值达到 346 ,几乎在任何非零负载下分离都是更优的选择,两种硬件上的结论差距这么大主要是因为传输带宽差了将近 30 倍,γ 的差异相对没那么大( 0.087 vs 0.130 ms/token ),所以比值主要是被 transfer_rate 拉开的。这个结论确实感觉很不合理,直接原因就导致路由决策非常单一,理论上能充分展示路由决策的机器本人无钱无时间找到(谁来帮我考算分期中!),于是懒得改了。

此外还实现了一个输出长度预测器,因为路由需要估算 decode 阶段的代价,而 decode 代价正比于输出长度,但输出长度在请求来的时候是未知的,用了一个在线的贝叶斯预测器,按 prompt 长度分桶,每桶内维护历史输出长度的统计,新请求来了用对应桶的均值作为预测,桶内样本不足时 fallback 到全局均值,这部分比较粗糙,输出长度预测本身就是一个很难的问题,实际上即使是 vLLM 这样的成熟系统目前也还没有特别好的解法,这里的实现只是为了让路由可以跑起来,准确性有限。

测试和结果

写了一个 Poisson 到达过程的 benchmark ,模拟真实服务里请求按泊松过程到达的场景,固定到达率 λ,跑固定时长,然后统计完成的请求数、端到端延迟的分布、以及 drop 的请求数,这比简单的串行测试更接近实际的服务场景,因为串行测试本质上是测单个请求的延迟,没有并发,没有排队,和真实负载差距比较大。

结果上,在 RTX 4090 × 8 的环境下, adaptive 路由在中等到达率下的吞吐和延迟比 collocated 有一定改善,在 H20 上分离路径的优势更明显,和代价模型的预测基本一致,但实际的性能数字和成熟框架比是没有可比性的,因为缺少了 CUDA Graph 、 Flash Attention 、算子融合等优化,这里就不列具体数字了,主要是看各策略之间的相对趋势是否符合理论预期,从这个角度来看结果是比较合理的。
性能出现巨大问题的原因还有 disagg 路径没有像 collocated 做那么多小优化, such as cotinious batching 等等,在项目的文档中我做了具体说明。

另外一个有意思的观察是,在 H20 上 adaptive 的峰值吞吐反而低于 RTX 4090 ,原因是 H20 的 decode 步更快(β = 33ms vs 51ms ),更多请求在 collocated GPU 上就快速完成了, disaggregated 路径的利用率相对
更低,多卡的优势没有完全发挥出来,这有点反直觉,但想清楚之后也是合理的,更快的 decode 反而减少了分离的必要性,加之我较为 naive 的 paged attention 实现(肉眼可见有一处就可以改为 reduce 求和),使得 max_request_num 调大了就会影响 TTFT 等乱七八糟的事,本人又买不起 autodl 的 H20 * 4 呜呜呜,就这样吧。

一些感受

实现上没有做 CUDA Graph 、 Flash Attention 或量化这些会显著影响性能的优化(实际上懒了写不了了),主要是想保持每一层的逻辑足够清晰,方便对照论文理解设计决策,也方便文档解释,所以性能上和成熟的推理框架没有可比性,仅仅是作为理解系统设计的实践项目。

写完之后最大的收获可能不是哪个具体的技术细节,而是对整个系统各层之间的依赖关系有了更清晰的感受,代价模型的准确性依赖 micro-benchmark 的质量, micro-benchmark 又依赖引擎本身的实现是否足够接近真实推理路径,路由的效果依赖输出长度预测的准确性,调度器的策略影响 profiling 时测出来的 interference 数值,这些依赖关系在读论文的时候是模糊的,实现一遍之后会更具体地感受到每一层的假设在什么条件下成立,什么条件下会失效,以及各层之间的耦合程度,这种感受很难单纯通过读代码或读论文获得。

已经放到了 github 上,文档里对每层的设计决策有比较详细的说明。

3D Reconstruction Series

引言

更新,已决定停止更新( x


可以看到本文的 publishDate 是 4096-16-64, 实际上的 publishDate 是 2026-02-10 。
本文的初衷是一个长期更新的 3D recon 系列论文阅读,之前其实已经发过了一些该领域的论文的精读了,但是显然精读必然是不可长期持续的。因此,我想以本文——一个系列的形式记录对大多数论文的浅要阅读,当然如果有特别重要的论文,我也会单开一篇文章进行精读的。

本文的 cover image 是一个词云,记录了本文包含的工作的名称,希望它能不断地更新,成为一个 3D recon 领域的词云图谱。

CUT3R

CUT3R 的输入是视频序列,但是也可以 unordered (据作者所言训练的时候是无序训练的,但是推理的时候推理的时候是 dataloader 先计算重合率来进行初步排序。),使用一个 feed forward 网络预测 camera parameters 和点云。

cut3r

然后是一个 recurrent 模型,每一帧输入的时候添加一个 pose token 然后经过 encoder 和 decoder ,之后使用交叉注意力更新,之后再使用不同 head 来从中提取 output 。

显然这样缺少修正,对于长序列容易造成偏移。但是作者似乎也提到了一个 revisit 机制,在输入结束之后拿着全局的来做之前的预测,在 7scene 上的 acc 和 comp 是有改善的,但是 NRGBD 不怎么明显。

此外,作者也说因为数据集质量的原因,采用的 head 即使已经有一个 pose head 和 local points head ,也仍然要加入一个 world ptshead (缺乏高质量的数据集)。

">

是一个相对来说比较有趣的东西,模型结构如下:

pi3

首先与之前的最大不同是它没有显式地选取参考帧和一个特定的 scale factor ,像 VGGT 就是先选取了一个 ref frame 然后做重建,但是重建质量受 ref 影响很大,因此选择了一个方案,就是一次性将所有帧全部输入,所有帧之间均平等,然后 inference 出一组相对位姿和局部点云,这样就能规避确定某一个 frame 作为坐标原点造成的不确定性问题。

但是仔细一想,仍然不怎么好避免一个 ref 的问题,首先,在一个 batch 内部,虽然我们预测的是一组相对位姿,但是直觉上感觉仍然是把某一帧与其他帧不融洽所导致的原先的那种大的,显著的,偶然性的损失转化为了现在的看起来不明显的、高一致的、所有帧都有的系统性损失。但作者通过实验证明了损失会变小,其实这也是比较好解释的,因为原先的可能是依赖依赖……这种单向参考,而则进行了交叉注意力计算,仔细想来确实会更好。

其次,交叉注意力的复杂度大概是,显然对于长序列是不可接受的,作者训练和测试的时候均采用了有限个 batch 内 frame 的做法,但对于实际的长序列的话,感觉并不是很好做。如果切片进行拼接的话,显然也会面临 ref 的选择问题,但是这时候是一个 scene 之间的拼接,感觉确实会降低很多错误,如果分层做的话,也会降低误差,总之感觉似乎确实是一个不错的方案。

DA3

DA3 是字节 seed 的一个项目,可以说是力大飞砖,充分体现了工业界解决问题的规模( x 。

da3
DA3 的主要创新点在于:

  • 更简单的模型,作者的意思是 VGGT 即使结构很简单,但是由于其在 DINO 后接 AA 层的操作,因为 AA layers 是新训练的,因此过程中可能数据的利用率不高。而 DA3 选择了只利用 DINO 这一个方案,通过在 DINO 的层中变形数据完成了 AA 层所做的事情。因此, DA3 的几乎所有参数都是预训练过的,而 vggt 则有 的参数是从头开始训的,这是 DA3 的简洁之处。

  • 预测任务的简洁性。相比于 VGGT 通过不同 head 得出了不同结果, DA3 则使用了一个更新的表达方式: Ray-depth 表达,具体来说就是使用一个 Dual head 来分别输出一个像素的深度信息和光心与之相连的射线的信息,从而天然地同时包含了点云和 pose 信息,而且在设计 loss 的时候是可以加入一致性信息的。相比与 vggt ,这似乎加强了一致性,也提高了数据利用率,感觉 pose 和 pts3d 反而是不容易加入一致性的,作者做的消融实验也证实了这一点。

  • 使用 teacher 标定数据,首先训了一个 teacher 模型用于给深度不好的 frame 重新生成 depth ,之后依照这个 depths 训练。感觉最终效果也很依赖这个 teacher 模型。

但是, DA3 的弊端也有一些,他的效果确实非常好,但是阅读之后才发现他是用 128 x H100 训练的,这个规模确实有点难以复现。小算力情况下上面两条结论似乎很有帮助,可以尝试。

MapAnything

首先是 Meta 的项目,和 VGGT 难道不构成什么竞争关系嘛()

主要创新点在于他的输入很有意思,不同于 VGGT 还有以往的重建工作只输入图像序列, MapAnything 支持多种多样的输入,对于每一个输入都会通过一个 encoder 最后对齐到 DINOv2 输出的 image token 上,然后就是正常处理的流程,不过似乎它多加了一个 scale token ,用于预测 scale 信息。

mapanything

感觉其利用了 nlp 里面的多模态,证明了给定不同类型的输入其预测的准确性与相应的专家模型性能相似,这是很有价值的,因为他减少了很多训练量(虽然也是在 64xH200 上训了 10 天)。

另外一个比较有趣的地方在于,他最后的点云数据不是直接输出的,而是由 depth , ray , pose 联合输出,这解耦了 VGGT 的冗余预测模式,而且在设计 loss 的时候能保持更好的一致性,感觉这个跟 DA3 输出 Depth-ray 的做法还是很像的。

不过其缺点也非常明显,首先对于长序列情况下,其仍然没有摆脱的处理复杂度;其次模型是 offline 的,不过感觉各有各的应用场景;最后就是推理速度和显存占用,推理速度在 100frame 的时候就已经接近 10s ,而且这时的显存占用也已经来到了 65G 左右,即使采用了作者提出的 Mem Efficent 策略,即在 dpt 头采用串行计算策略也是 20G 左右,似乎有点太大了( x

此外,作者表示了在输入过程中模型无法对噪声数据进行处理,也就是说潜在的噪声可能会污染整个 transformer 的内容,另外融合时机是在 encoder 之后进行,而且是简单的相加,可能有更精细的融合方式。

AnySplat

anysplat

与之前讲过的大多数点云重建的工作不同, AnySplat 是 3dgs 重建。具体来讲就是他在 vggt 的基础上进行改造, backbone 与 vggt 相同,但其 head 则是一个 gaussian head, 一个 depth head ,还有一个 Camera head 。然后通过一个可微体素化将原本稠密的高斯球聚合到一起,训练的时候则监督:

  1. 每一帧位置的 rgb loss

  2. depth 的深度与 gaussian depth 的差异损失

  3. 相机参数与 vggt 预测出的损失

  4. 模型预测深度与 vggt 之间的深度差异

首先, 2 的 loss 保证了其几何一致性,也就是让不同视角的深度尽量保持一致,可以避免分层现象。此外,文章作者说他们实现了一个 Differentiable Voxelization ,可以有效解决生成的稠密高斯球产生的复杂度问题。

总体来说,这是一个高度模仿 vggt 的工作,只不过换了一下 head 和输出形式,其余部分都差不多。此外为 offline 的重建,看上去速度似乎还可以,但是同样面临长序列问题。另外,固定世界坐标系为第一张图片,去监督每一个绝对位姿是否正确,似乎也是存在所述的归纳偏置问题的。

RayZer

rayzer

令人耳目一新的自监督模型,训练过程只需要图片而不需要 gt 的 pose 和内参,训练过程大概是这样的:

  • 首先输入张图片,将其分为两个集合。

  • 然后模型通过 Camera Estimator 模块,预测出 pose 和 intrinsics 。

  • 之后对于 ,模型根据其对应的预测出来的 和本身的图片输入,生成场景的 token.

  • 然后对于,模型选择通过 预测出 然后监督 之间的损失,然后更新所有的值。

因此,推理时的大致步骤大概就是先把场景的已知几张图片输入得到 ,之后针对一个特定的 pose ,计算一个光线图,之后输入到 rendering decoder 里得到在这个特定的 pose 下的 rgb 图片。

感觉和 nerf 好像,都是一个隐式的表达整个场景,不过不同的是 RayZer 是一个更直接的模型,图里的三个模块每个都是 8 层 naive transformer , loss 仅由最后的 rgbloss 和 LPIPS loss 决定,感觉挺聪明的。不过感觉 rendering 部分采用的表现形式——类 raymap 形式似乎真的挺好用的。

另外,值得注意的是第一部分,在预测 pose 和 intrinsics 时,直接选取了中间帧作为参考帧,使得模型能跨越更长的距离。此外,如果说我们在第一部分就引入 ,能否实现定位功能?不过作者似乎做了消融实验,发现在训练的时候,从图像特征中提取几何关系比从一个未成形的 中提取容易得多。但是我觉着可以在 rendering 部分再添加一个 decoder 用于定位。

另外,这个模型完全打败了 LVSM (一个有监督的模型),感觉是一个非常惊艳的工作,看项目主页的 demo 视频感觉真的很不错啊。

Spa3R

spa3r

首先是一个自监督的模型,模型的 backbone 设计的有点复杂:

我们给出一个场景的 views ,然后将 views 分为 context view 和 target view ,首先将所有 views 通过一个改造过的 vggt (似乎是只引入了 head 之前的部分),改造内容是在 context Views 的 AA 层那里把 Target Views 给 mask 掉,然后得到 Context Views 的 feature 和 Target Views 的 camera token 和 Feature ,之后,数据流向两条路径:

  • Context views : 与一组可学习的 通往 Encoder ,然后得到 作为空间的隐式表征。

  • Target views : camera tokens 通过 camera head 生成 camera embeds ,然后与 一起输入到 Decoder 里生成对 Target views 的预测过的 feature ,然后将得到的预测 feature 与 进行监督得到 loss 。

推理的阶段我们就只看 Context Views 得到的 ,将与 qwen2.5 vl 得到的 输入到一个Adapter里,然后将这个 adapter 和 text prompt 输入到 llm 里得到最终结果。

首先,肉眼可见这项工作把大量的其他工作缝合到了一起, Target View 阶段用了 DINOv3 和 VGGT , 的后续处理用到了 qwen2.5 vl ,但是这篇文章叫 Spa3R 啊, Dust3R 被放到哪了呢?然后可训练的内容只有 Encoder 和 Decoder ,仅 6 层 Transformer ,而且通过两个作为 loss 进行训练,训练结束之后即丢弃 Decoder ,保留训好的 Encoder 和 q 。然后后续还有一个针对 Adapter 的一个微调,让其学到怎么生成一个合理的融合

模型做了几个消融实验:

  1. Target Views 阶段作者证明了同时使用 VGGT 和 DINO 会更好(包含语义和空间信息),这是一个比较显然的结论。

  2. 提取出一个场景 表征是一个更好的手段,相对于现有的几个类似于 VG-LLM 简单把所有特征输入到 llm 里效果更好(但是只提升了 3 个点,感觉有点低于预期,考虑到第二阶段训练只进行了 1 个 epoch ,有没有可能是训练量不够?我也是第一次读 VLM 相关的文章(),不过看具体的比分, Multi-Choice 涨分了,而 Numerical 几乎没变,确实是 make sense 的)。

  3. pose embedding 的影响, PRoPE 比 plucker 更好。

  4. Mask Ratio ,这也是一个比较显然的消融实验。

  5. Adapter 使用提高了点数,比较 make sense 。

模型只在 ScanNet 和 ScanNetpp 上进行了 pre train ,使用了 8 张 5090 进行训练,在 VSI-Bench 上达到了 58.6 的水平,超过了之前的大部分 model ,查看现在的 VSI-Bench Leaderboard ,其性能也是处于前列的(不过论文里的表格好像有些数据有点不对?可能有更新吧)。算是为领域开了一个新坑(),自监督看上去也不错()。

看上去这篇文章正在投 CVPR ,是笔者写阅读笔记的两天前才登上了 arxiv ,也不知道中没中,方法是很有趣

Spann3R

结构很复杂,首先大部分模型权重继承自 Dust3r ,然后模型的 backbone 大致如下:

spann3r

  • 预编码 :首先将一帧输入到 ViT Encoder 得到一个 ,此时我们手上还有一个上一帧的

  • 查询记忆: 根据 ,我们可以从历史记忆中查询出一个 来作为下一步的输入。

  • 主要推理部分: 之后我们将这两个 feature 输入到 Target Decoder 和 Reference Decoder ,这两个 Decoder 会做 self attention 和 Cross attention 然后分别得到

  • Heads : 对于 ,在推理阶段我们会使用一个 query head 来提取出,然而在训练阶段我们也会加入一个 head 将其转化为点云和置信度来监督训练;对于 ,我们会通过一个 reference head 将其重建出点云和置信度。

  • 记忆: 之后,根据 ,我们将其通过一个 Memory encoder + MLP head 生成一个 ,然后根据这个和点云通过一个 Memory Encoder 生成 ,之后会对已有记忆去重, 如果工作记忆已满剩下的就会进长期记忆然后做进一步处理。

这是一篇 24 年的文章了,主要创新点就在于他改良了 Dust3R ,使得可以对多个图片输出一个一致的全局坐标系下的点云,此外使用记忆方法,分层处理记忆。

但很显然的是,虽然该方法加入了记忆,但是记忆看上去也是近期记忆的方案,客观上因此而存在长距离漂移的现象,此外,如果遇到 reloop 现象,记忆是否能健康提取也会是一个比较大的问题。

做的消融实验大致有这几个:

  1. 关于记忆方面的消融实验,去掉长期记忆会引起很大的漂移现象,而注意力不截断的话也会引发噪声的干扰

  2. 关于长期记忆应该取多大:作者发现 1000-2000token 的过程中漂移得到极大修正,但是 4000+之后就不会有明显的提升,因此最后作者选择了 4000.

  3. Dust3R 采用了 exp confidence function ,本文将其改为了 sigmoid ,事实证明是有所改善的。

Flow4R

一个局限性很大的三维重建追踪方案,不过在表现形式上很有新意。

模型的 backbone 很优雅,首先接收两张图片作为输入,通过共享权重和 cross attention 的两个对称 encoder-ecoder-head 结构得到每张图的 其中, 是相机坐标系下的点云, 是一个场景流,描述每一个像素如何从本张图片移动到下一张点云,之后还有一个 指示哪个像素在求解 pose 的时候最可靠,最后的 是全局的置信度。

flow4r

得到这些元素之后,可以首先将 pose 通过最小二乘法求出:

是由 得到的,得到 pose 之后就可以做位姿流和场景流的分解,然后很多下游任务就可以进行处理了。

针对于长序列数据,作者提出了将第 1 张 frame 作为锚点,后续的每一张都与之输入处理,好处是可以通过 L2 norm 来归一化尺度,但是坏处也非常明显,一是稍微长一点的序列,就会出现遮挡现象,模型目前来看没有一种很好的应对方式;二是极其依赖第一张 frame 的质量,鲁棒性不算太好。观察其论文里呈现的 demo ,看起来也通常是对一个角落 or 一个相似视角区域做的重建,完整场景重建效果存疑。

此外,作者竟然只做了一个消融实验(能中吗?)对比了三种不同的网络预测和监督变体 :

  • 预测场景流 ,并用真实的  进行损失监督 。

  • 预测场景流 ,但用目标帧的真实 3D 点位置  进行监督 。

  • 直接预测目标帧的 3D 点位置 ,并用真实的  监督(场景流则通过简单的减法推导: ) 。

消融结果:实验证明,直接预测并监督 的性能最佳 。因此后来直接预测的实际上是

总体来说,这篇工作证明了一点,可以通过引入流的方式来完成 Dust3R 这种结构从静态到动态的拓展,但确实局限性很大。

这项工作似乎还没有开源()

AMB3R

把三维体素引入到了重建中,使得模型能够真正地从空间角度来考虑重建任务。简而言之就是之前的重建采用的 ViT 将图像分为一个一个 patch 造成隐式几何中缺乏空间紧凑性约束,于是论文作者想了一个办法把空间紧凑性加入到了 backbone 当中。

amb3r

大致的 backbone 分为前端和后端,其中,前端继承了 VGGT 的网络和参数,一张图片进入之后会经过 Encoder 得到一个初步的 feature ,然后数据的主题是向 decoder 移动,但是这部分 feature 也会使用一个 scale head 预测一个绝对尺度。

然后,进入 decoder 的 feature 会对 keyframes 做 cross attention ,这里的 keyframe 就可以理解为场景的隐式表达,经过该过程之后, decoder 就会输出一个 pointmap 和一个 confidence ,在推理阶段,之后会有一个门控机制:如果置信度足够高,那就直接进入下一阶段,反之则会将点云和 feature 变为体素,然后通过一个 point transformer 优化该体素的 feature ,之后再会逆变换变为 2Dfeature ,之后我们会将该 feature 注入到前端的 decoder 中,重新拿到一个高级的点云。

然后我们拿到了当前帧的点云以及物理尺度,然后系统会将该结构放大/缩小,然后根据 keyframes 和 VGGT 预测出的 pose 将该结构拼接到大的全局点云中,最后我们会评测该点云是否可以成为 keyframes ,然后将其处理掉。

将体素引入到点云重建里很厉害,作者做的几个消融实验:

  1. 移除了基于 sparse voxel 的后端,转而使用一个 2D 做 alternate attention 的后端,发现精度不如之前。

  2. 去除了零卷积机制,发现模型短时间内根本就未收敛。

  3. 在算 loss 的时候去除了 scale 发现效果变差,也就是说模型需要去专注思考几何结构。这是在训练阶段做的事情

这篇文章的训练成本非常非常的低,依赖于一个已经训好的 VGGT ,只训练了微调点云特征的一个 point Transformer 和一堆 head ,感觉非常有启发性非常厉害,同时也中了 CVPR2026 ,符合预期(似乎是 Spann3R 的续作)

VGGT-SLAM

我说这是一篇数学论文,文中没有训练任何模型,仅仅是介绍了一种局部点云拼合办法。

vggt-slam

顾名思义,这篇工作基于 VGGT 输出的点云和 pose ,作者认为 VGGT 预测出 pose 和局部点云之后直接进行 Sim(3)变化为全局点云是有问题的,主要灵感来自于传统 CV 里面的双目立体视觉:相机之间的单应性矩阵或者说是本征矩阵并非仅仅包含了 pose 中进行的旋转、平移,更有一些拉伸,透视等等等。具体来讲就是 VGGT 预测出的点云深度包含了相机的射影形变,直接使用 Sim(3)方法来还原是不准确的。

因此,作者转而使用了 SL(4)进行点云的对齐,具体来讲,当 VGGT 得出了点云和 pose 之后,会进行以下几个操作:

  • 对于一个子地图里的帧,作者选择相信 VGGT 的质量,作者在代码里设置了一个 submap_size 参数用于控制子地图的大小。

  • 对于不同子地图之间,因为我们想得到一个在不同坐标系下共享的三维点,所以作者这里采用了一个很聪明的办法,将上一个子地图的最后一帧重复输入到下一个子地图里,这样 VGGT 的输出就包含了相同图片在不同坐标系下的点云,由此可以建立点与点之间的对应关系。

  • 之后根据传统的一些算法,可以计算两个子地图之间的 SL(4)矩阵,到这里第一步就算完成了

  • 下一个步骤就是全局对齐,作者也写得太数学了吧:

  • 具体来讲,作者构建了一个基于最大后验估计的非线性因子图,目标是最小化所有子地图之间的相对单应性误差:

    $\hat{H}=argmin_{H\in SL(4)}\sum_{(i,j)\in\mathcal{L}}||Log(H_{i}^{-1}H_{j}(H_{j}^{i})^{-1})||{\Omega{ij}^{H}}^{2}$

  • 然后引入各种优化器,这里我的数学太烂了( x )根本看不懂,只知道他是需要迭代优化的。

  • 嗯嗯,所以这样我们就可以得到一个后端,对于每一个子地图,都给出了一个将其变换到潜在全局坐标系下的 SL(4)矩阵,从而消除了 Sim(3)变换带来的问题。

此外,文章还提出了一种 reloop 机制,就是说在一个子地图待输入的时候,系统会利用 SALAD 描述子去寻找历史子地图中是否有相似的图片,若有,系统就会选择将那张图片作为共享帧,我们这时候就会有多个相对的信息。

总体来说,这篇工作就是提供了一个偏传统的对齐方法,比较优雅,但是很显然缺点也很明显,首先对于单个子地图,该工作完全信任 VGGT 的输出结果,缺乏鲁棒性;其次,其得出对齐是通过迭代优化得出,相对于直接拼接会慢上很多,另外有太多的查询操作(如 reloop ),感觉复杂度还是有点高的。

不过可以从上图看到,他确实改善了点云拼接时可能产生的分层的质量。但是,查看其 github 里的 issue ,似乎稳定性存疑:

Due to potential randomness in our approach caused by RANSAC, we report the average performance over five runs, which have a low spread (small standard deviation) as shown in Sec. 5.5.

而且那个 issue 到最后作者都没有回答,感觉有点尴尬( x

学习笔记:Tensor Parallelism(TP)

引言

经历了一些对未来选择的思考之后,最近在了解 mlsys 相关的内容,本文即为对 TP 的理解和总结,目前网上已经有大量的博文详细介绍了 TP 的实现细节,本文主要是为了自己未来查阅方便而写的文章,欢迎大家指正。

TP简介

Tensor Parallelism 是在 DP, MP 之后提出的一个方法,由 Magatrion-LM 首创。其出发点在于 DP, MP 仍然需要单卡在计算时凑齐一个完整的 layer 的参数和各种激活值、梯度、优化器状态,当一个 layer 过大的时候,单卡就放不下了。
而 Tensor Parallelism 将模型的计算拆成分布式的了,使得一层能够分布于不同卡上进行计算。

Transformer-like model

一个经典的 Transformer 模型的架构大致如下图:

transformerarch

可以看到,一个 layer 主要由 Attention 和 MLP 层组成, TP 的关键优化点也就是在这两层上,下面将具体说明。

MLP

我们先从 MLP 层开始,简而言之,一个 MLP 层的数学描述大致这样:

其中:

一般来说,

我们先考虑不进行 TP ,仅仅进行单卡计算:

单卡forward

参数量:

计算量:

激活量:在 backward 里考虑。

单卡backward

首先对 dropout 反向:

这一步的 FLOPS 差一个数量级,可忽略不计,另外使用 表示

然后对 进行反向:

其中

这一步的 FLOPS 为

GeLU 的 FLOPS 几乎也可以忽略不计。

然后对 进行反向,几乎与 相同。

因此整个过程的 FLOPS 为 ,为前向传播的两倍。

然后我们从激活值占用角度分析,在没有梯度检查点的情况下,我们有:

1
2
3
4
X (BS, d_model) use for compute L_W1
H = XW_1 (BS, d_ff) use for compute the gelu
A = GeLU(H) (BS, d_ff) use for compute L_W2
Dropout mask(BS, d_model) use for Dropout

TP forward

sd

我们进行这样的切分方式:

1
W_1 -> (W_11, W_12, W_13, ... W_1n) # W_1i: (d_model, d_ff / n) 

这样我们在输入 X 的时候全部注入,然后得到:

1
H -> (XW_11, XW_12, XW_13, ... XW_1n) # XW_1i: (B, S, d_ff / n)

值得注意的是,我们选择按列切分 使得我们得到的结果是可以独立通过 gelu 的,省去了这一步通信的麻烦。

之后考虑

我们选择将 进行这样的切分:

1
2
3
4
5
6
7
W_2 -> [
W_21,
W_22,
W_23,
...
W_2n
]

之后,显然我们现在可以每张卡计算XW_11 @ W_21,而且他的形状就是最后矩阵的形状,
因此,我们算出来然后最后采用 all reduce 就可以得到最后结果啦。

ok ,我们现在对这整个过程进行分析:

  • 参数量:
    显然,我们现在把所有参数分散到了多卡上,而且分散均匀,

  • 计算量:

但是这里还要考虑一个问题,就是最后 reduce-all 操作还要对所有激活值进行累加,但是这部分数量级过小,可忽略。
  • 激活量:在 backward 里考虑。

TP backward

在每张卡上的前向是:

由于 AllReduce 之后每张卡上的 Z 完全相同,所以上游传回的梯度也完全一样,不需要额外通信。

此后,每一步的计算基本上与单张卡相同,但是要除以

因此,每张卡的反向 FLOPS 为:

然后,之后需要注意的是我们在反向传播的最后仍然需要一步 all-reduce ,因为我们此前计算的都是独立的梯度。

激活值的占用:我们有:

1
2
3
4
X (BS, d_model) use for compute L_W1
H = XW_1 (BS, d_ff / N) use for compute the gelu
A = GeLU(H) (BS, d_ff / N) use for compute L_W2
Dropout mask(BS, d_model) use for Dropout

Attention

单卡forward

输入数据:

1
2
3
4
5
6
7
8
9
10
X (B, S, d_model) 
X_h (B, S, h, d_head) W_Q (h, d_head, d_Q) W_K (h, d_head, d_K) W_V(h, d_head, d_V)
# 注意到在单卡情况下我们这一步计算 Q, K, V 通常不做维度划分,但可以这么理解,方便后续对 TP 的理解
Q (B, S, h, d_Q) K (B, S, h, d_K) V (B, S, h, d_V)
Q @ K.transpose -> S (B, h, S, S)
S @ V -> (B, h, S, d_V)
reshape -> (B, S, h *d_V)

# 接着引入一个 W_O: (h * d_V, d_model)
O (B, S, d_model)

ok ,对整个过程清晰之后我们便可以分析其各个指标:

参数量:

通常来说这几个都相等,所以总参数为

计算量:

操作 形状 FLOPS

因此,总的 FLOPS 为:

需保存的激活值:

Tensor shape num

单卡backward

首先我们做 的反向:

加起来是

然后我们回到

这一步的 FLOPS 为

然后经过 Softmax 反向, FLOPS 可以忽略,然后计算 Q, K , FLOPS 为

之后对 做反向,权重梯度和输入梯度均为 ,共计为 12 。

因此,总反向 FLOPS 为:

为前向的两倍,所以我们在这里也可以认为反向传播的 FLOPS 为前向的两倍。

TP

显然这时我们就可以完全将 head 分到多张卡上,所有的几乎均乘上一个 即可。

但此时仍然需要注意的是,我们得到 O 之后仍然需要 all-reduce ,这与 mlp 是一样的。

先写到这里.

HPCGames 题解 D E 题

在上一篇文章中,我们介绍了 HPCGames 题解 A 、 B 、 C 题的解决方案。本文将继续探讨 D 、 E 题的解决方案,深入分析每道题目的挑战和我们的应对策略。

D. Hyperlane Hopper

HPCGames 题解 A B C 题

A 题

B 题

这里又来到了经典的小北问答环节,结合一些理论知识和具体论文的查阅,我们可以对题目进行详细的分析和解答。

1. Amdahl & Gustafson

某程序的代码中 10% 必须串行执行, 90% 可完美并行。

  • 根据 Amdahl’s Law ,无论核心数如何增加,该程序的理论最大加速比极限是 ____ 倍;

  • 若在 10 核系统中通过扩大问题规模来保持每核计算负载不变,根据 Gustafson’s Law ,该系统的加速比将达到 ____ 倍。

    首先,根据 Amdahl 定律,加速比 S 可以通过以下公式计算:

    其中 P 是可并行部分的比例, N 是处理器的数量。对于该问题, P = 0.9 ( 90% 可并行),串行部分为 0.1 ( 10% 必须串行)。当 N 趋近于无穷大时,公式简化为:

    因此,该程序的理论最大加速比极限是 10 倍。

    接下来,根据 Gustafson 定律,加速比 S 可以通过以下公式计算:

    在 10 核系统中, N = 10 , P = 0.9 ,因此:

    因此,在 10 核系统中通过扩大问题规模来保持每核计算负载不变,该系统的加速比将达到 9.1 倍。

2. OpenMP

以下代码使用 OpenMP 并行执行循环:

1
2
3
4
5
6
int sum = 0; 
#pragma omp parallel for
for (int i = 0; i < 100; i++) {
sum += i;
}
printf(" sum = %d\n" , sum);

关于该代码,请问以下说法中正确的是 ____ 。

选项 描述
A 代码一定能正确计算出 0 到 99 的和( 4950 )
B 代码存在数据竞争, 结果不确定。
C sum变量默认为private,每个线程有自己的副本。
D OpenMP 会自动为sum变量添加原子操作,保证结果正确。

正确答案是 B 。

解释如下:

  • 选项 A 是错误的,因为代码中存在数据竞争,多个线程同时修改共享变量 sum,导致结果不确定。
  • 选项 B 是正确的,因为在并行执行时,多个线程可能同时读取和写入 sum,导致数据竞争,从而使得最终结果不确定。
  • 选项 C 是错误的,因为 sum 变量在默认情况下是共享的( shared ),而不是私有的( private )。因此,所有线程都访问同一个 sum 变量。
  • 选项 D 是错误的,因为 OpenMP 不会自动为共享变量添加原子操作。要确保结果正确,需要显式地使用 #pragma omp atomic 或其他同步机制来保护对 sum 的访问。

3. 低精度

已知 IEEE 754 标准的 FP32 拥有 8 位指数位。请问:

  • BF16 拥有 ____ 位指数位,____ 位尾数位
  • NVFP4 拥有 ____ 位指数位,____ 位尾数位

提示:可以查阅资料,了解 NVFP4 如何在低精度下保持较高的数值范围和动态范围。

经查阅资料可知: - BF16 拥有 8 位指数位, 7 位尾数位 - NVFP4 拥有 2 位指数位, 1 位尾数位
NVFP4 比较特殊,他只有 4 个 bit ,显然如果直接使用的话,其范围会很小,精度也不理想,但经过查阅资料可知:
NVFP4 首先将一组数视为了一个块,一个块中会共享一个高精度的 scale factor ,确定大致的数量级,然后 NVFP4 只存储每个数相对于这个 scale factor 的偏移量,这样就能在保持较大数值范围的同时,使用更少的位数来表示每个数,从而提高了存储效率和计算速度。

4. MPI 通信

4.1 基本原语

4 个进程执行以下代码,每个进程有局部值 local_val ,操作后每个进程都有所有进程的值。

1
2
3
4
5
int rank; 
MPI_Comm_rank(MPI_COMM_WORLD, & rank);
int local_val = rank; // rank 为进程编号, 0~3
int recv_buf[4];
/* 填这一行代码 */

4.2 通信器

创建一个 2 维笛卡尔拓扑,尺寸为 2×2 ,行优先排列,允许环绕连接。

1
2
3
4
MPI_Comm comm_cart; 
int dims[2] = { 2, 2} ;
int periods[2] = { 1, 1} ; // 环绕连接
/* 填这一行代码 */

4.1 基本原语

可以使用 MPI_Allgather 来实现该功能。代码如下:

1
MPI_Allgather(& local_val, 1, MPI_INT, recv_buf, 1, MPI_INT, MPI_COMM_WORLD); 

这行代码会将每个进程的 local_val 收集到所有进程的 recv_buf 中。

4.2 通信器

可以使用 MPI_Cart_create 来创建一个二维笛卡尔拓扑。代码如下:

1
MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, & comm_cart); 

这行代码会创建一个 2x2 的笛卡尔拓扑通信器 comm_cart,并允许环绕连接。

5.NCCL 延迟

在深度学习的并行推理与训练中,进程之间会频繁进行集合通信操作。 NVIDIA 的开源集合通信库 NCCL ,提供了在 GPU 之间进行集合通信的高性能解决方案。

当在异构的硬件上进行大规模集合通信时,如何选择通信的算法将很影响集合通信操作的效率。为了解决这个问题, NCCL 的解决方案是:基于一套硬编码的调优常数,估算不同集合通信算法下的集合通信完成时间,由此选择最优的算法。

问题:在 NCCL 2.28 的默认调优常量中,用 NVLink 连接的两 GPU 、采用 Tree 算法和 LL 协议时,在估算时每跳(单步)的硬件延迟取值为 ______ µs 。

根据 NCCL 2.28 的默认调优常量,当使用 NVLink 连接的两 GPU ,采用 Tree 算法和 LL 协议时,每跳(单步)的硬件延迟取值为 0.6 µs 。

具体参考资料可见 NCCL Github src/graph/tunning.cc中的 151 行。

6. 高性能网络

Rail-optimized networking 与 Clos 都是高性能网络设计方案。以下说法正确的有:

选项 描述
A 在 Rail-optimized 网络中,来自不同 HB 域( High-Bandwidth Domain )但具有相同 local rank 的 GPU 会被连接到同一个 rail switch 上,以减少跨域通信的延迟
B 常见部署模式下, Rail-optimized 网络相比传统 Clos 网络的主要优势是完全不需要 Spine 层交换机,因此可以大大节省网络设备成本
C Clos 网络因其使用 Spanning Tree Protocol (STP) 而在大规模部署时存在扩展性问题,这是 Rail-optimized 网络要解决的核心问题之一
D Rail-optimized 网络保证了任何情况下集群内任意两个 GPU 之间都能以网络线速(如 400 Gbps InfiniBand )进行通信,无论它们是否在同一个 rail 中
E NCCL 2.12 引入的 PXN 特性可以结合 NVLink 和 PCI 通信来优化网络流量,这个优化对于 Rail-optimized 网络尤为重要
F 对于 LLM 训练工作负载,最优的通信策略会将大部分网络流量集中在相同 local rank 的 NIC 之间,并且会多用 NVLink 等高速互联进行跨 rail 交换,这使得 Rail-optimized 架构特别适合此类场景

正确答案是 A 、 E 、 F 。

解释如下:

  • 选项 A 是正确的,这是 Rail-optimized 网络的核心定义。 在这种架构中,网络拓扑是根据 GPU 的 rank 进行物理隔离的。例如,所有服务器上的 0 号 GPU 都连接到同一组交换机( Rail 0 ), 1 号 GPU 连接到另一组( Rail 1 )。这使得在进行数据并行( Data Parallelism )训练时, AllReduce 等操作只需在同一个 Rail 内进行,无需跨越复杂的交换层级,大大降低了拥塞和延迟。

  • 选项 B 是错误的, Rail-optimized 仍然基于 Clos 架构,通常需要 Spine 交换机。 Rail-optimized 描述的是 Leaf 层交换机与 GPU 的连接方式以及流量的导向方式,而不是一种去除了 Spine 的新型拓扑。对于大规模集群(超过一个 Leaf 交换机的容量), Rail 0 的 Leaf 交换机之间仍然需要通过 Spine 交换机互联,以构成一个完整的 Rail 0 网络平面。

  • 选项 C 是错误的, Clos 网络并不使用 STP ,且 STP 是传统以太网的痛点。 传统二层以太网使用 STP (Spanning Tree Protocol) 防止环路,这会导致大量链路被阻塞,带宽利用率低。而现代 Data Center Clos 网络(无论是基于 IP 路由的 ECMP 还是 InfiniBand )的设计初衷就是利用所有链路进行负载均衡,完全摒弃了 STP 。因此, C 选项描述的前提本身就是错误的。

  • 选项 D 是错误的, Rail-optimized 并不保证“跨 Rail”通信的效率等同于“同 Rail”。 Rail-optimized 的设计哲学是“专路专用”。虽然物理上可以通过 Spine 进行跨 Rail 通信(例如 Node A 的 GPU 0 发给 Node B 的 GPU 1 ),但这通常不是最优路径,且可能面临 oversubscription (收敛比)的问题。实际上,这种架构倾向于利用 E 选项和 F 选项提到的技术来避免在网络层面上进行跨 Rail 数据传输。

  • 选项 E 是正确的, PXN (PCIe/NVLink Cross-NIC) 是解决 Rail 架构灵活性的关键。 在 Rail-optimized 网络中,如果 GPU 0 需要向网络中的 Rail 1 发送数据,传统的路径非常低效(走 PCIe -> CPU -> NIC -> Switch ->…)。 NCCL 的 PXN 特性允许 GPU 0 通过 NVLink 直接把数据传给同机的 GPU 1 ,然后由 GPU 1 的 NIC (连接着 Rail 1 )发送出去。这相当于在节点内部利用 NVLink 完成了“变轨”,从而充分利用 Rail 网络的优势。

  • 选项 F 是正确的,这准确描述了 LLM 训练中的混合通信模式。 在 LLM 训练中,通常结合了数据并行( DP )和模型并行( TP/PP )。

    + TP (Tensor Parallelism) 流量极大,通常限制在单机内部,完全走 NVLink 。
    
    + DP (Data Parallelism) 需要跨机同步梯度,流量发生在相同 rank 的 GPU 之间,这完美契合 Rail-optimized 的网络路径。
    
    + 如果需要跨 rank 的操作(如 Pipeline Parallelism 的某些阶段或特定的 All-to-All ),结合 NVLink (节点内)+ Rail (节点间)是目前最优的策略。
    

7. GPU

NVIDIA 的 Hopper 架构引入了 TMA ( Tensor Memory Accelerator ) 以提升 GPU 内存访问效率。以下说法正确的有:

选项 描述
A 相比 cp.async , TMA 可以直接将数据从全局内存加载到共享内存,无需经过寄存器中转,从而能节省寄存器
B 在 cutlass 的异步流水线抽象中, Producer 调用 producer_acquire 获取空闲的 buffer stage ,完成数据加载后调用 producer_commit 通知 Consumer ; Consumer 则通过 consumer_wait 等待数据就绪,使用完毕后调用 consumer_release 释放 buffer
C 在使用 TMA 进行数据传输时,所有参与的线程都需要执行相同的 TMA 指令, TMA 硬件会自动处理线程间的协调
D Cutlass Pipeline 使用多级缓冲( multi-stage buffering ),通过 PipelineState 追踪当前读写的 stage index 和 phase ,实现 Producer 和 Consumer 之间的流水线重叠
E TMA 的 multicast 功能允许一次 TMA 操作将同一块数据广播到 Cluster 内的多个 Thread Block 的共享内存中,减少了重复的全局内存访问
F TMA 描述符( TMA Descriptor )需要在 kernel 启动前在 host 端创建,描述符中包含了张量的形状、步长和 swizzle 模式等信息, kernel 执行时通过预取描述符( prefetch_tma_descriptor )来减少首次 TMA 操作的延迟

正确答案是 B D E F.

解释 :

- 选项 A 是错误的。 Ampere 架构引入的 cp.async 指令同样也是绕过寄存器( Register File ),直接将数据从全局内存( GMEM )搬运到共享内存( SMEM )。
- 选项 B 是正确的。这描述了 Cutlass 异步流水线中 Producer 和 Consumer 之间的交互方式,符合 Cutlass 的设计理念。
- 选项 C 是错误的。 TMA 操作允许线程组内的线程根据需要选择性地执行 TMA 指令,而不是所有线程都必须执行相同的指令。如果所有线程都执行,会导致重复发射多个拷贝操作(除非有特殊的掩码处理)。这一点与 Ampere 的 cp.async (通常每个线程负责一部分)不同。
- 选项 D 是正确的。 Cutlass Pipeline 确实使用多级缓冲,通过 PipelineState 来追踪当前读写的 stage index 和 phase ,从而实现 Producer 和 Consumer 之间的流水线重叠。
- 选项 E 是正确的。 TMA 的 multicast 功能允许一次 TMA 操作将同一块数据广播到 Cluster 内的多个 Thread Block 的共享内存中,减少了重复的全局内存访问。
- 选项 F 是正确的。 TMA 描述符需要在 kernel 启动前在 host 端创建,包含张量的形状、步长和 swizzle 模式等信息, kernel 执行时通过预取描述符来减少首次 TMA 操作的延迟。

8. LLM

对于参数如下的一个标准的 Transformer-Decoder 模型,所有的 all reduce 操作都使用 ring all reduce 。假设一共有 4 张卡。

模型参数

参数
层数 32 层
隐藏层维度 (h) 4096
FFN 结构 两层线性层,中间层维度为 4h
序列长度 2048
Batch Size 32
优化器 Adam + 混合精度训练
精度设置 参数和梯度使用 fp16 , Adam 优化器状态使用 fp32 (包括 momentum 、 variance 和 master weights )

问题

请计算在以下三种并行方式下,进行一个 batch 的前向传播和反向传播,每张卡需要的发送量(以 GB 为单位):

  • 数据并行:每张卡上存放完整的模型,把 batch 均匀拆分到每张卡上,分别计算完成后对梯度进行 All-Reduce 操作

  • 流水并行:按层拆分模型放到不同卡上,只需要前向传播的时候发送 activation ,反向传播的时候发送 gradient 。(计算通信量时只考虑中间的卡)

  • 张量并行:对于 MHA 操作,按照 head 拆分到不同卡上。对于 FFN ,第一个线性层按照输出维度进行拆分,第二个线性层按照输入维度进行拆分

    计算过程如下:

    • 数据并行

      • 模型参数量:

      • 梯度大小:

      • 通信量:

    • 流水并行

      • 每层激活大小:

      • 通信量:

    • 张量并行

      • 单次 All-Reduce 大小:

      • 单次 Ring All-Reduce 通信量:

      • 总通信量:

9. UB 互联

在高性能计算系统中,集合通信( Collective Communication )的性能主要受带宽( Bandwidth ) 与延迟( Latency ) 两个因素制约。

NVIDIA 通过 NVLink 与 NVSwitch 构建 GPU 间的高速 Scale-up 互联网络,而华为则提出了 Unified Bus ( UB )协议,作为面向 NPU 的统一互联与内存访问机制。 UB 协议基于华为自研的 UB Switch 交换芯片,并通过高带宽物理链路 HCCS ( High-Capacity Coherent System ) 进行连接。

传统 AI 集群通常以 8 卡服务器为基本单元进行 Scale-out 扩展,而华为在 CloudMatrix 384 ( CM384 ) 架构中,通过两级 UB Switch 组网,将 384 颗昇腾 910C NPU 构建为一个统一的超节点( SuperPod )。在该超节点范围内,所有 NPU 均处于同一个低延迟的轨道优化网络中,实现全对等 Scale-up 互联。

CM384 进一步将 UB 网络划分为 7 个相互独立的物理平面。每颗 NPU 的 7 个 HCCS 接口分别接入不同的交换平面,从而保证大规模并行通信过程中,数据流在物理路径上完全隔离、无链路冲突。

问题

在 CloudMatrix 384 的标准满配部署方案中,为了支撑 384 颗昇腾 910C NPU 实现无收敛、全对等的 Scale-up 互联,系统采用两级交换架构。在该超节点的物理拓扑中,分别使用了:

  • ____ 个 Level 1 UB Switch
  • ____ 个 Level 2 UB Switch
  • 最终实现了理论上 ____ GB/s 的系统级聚合带宽

假设 switch chip 提供的单个 Port 可以提供 28GB/s 的通信带宽

该问题直接查阅华为 CloudMatrix 384 的白皮书即可得到答案。

10. Cache 行为分析

假设我们需要进行一个矩阵乘法

测试环境

为了简化分析,假设:

参数类型 配置
数据类型 double (8 Bytes)
L1 Cache 大小 4KB (4096 Bytes)
相联度 直接映射 (Direct Mapped, E=1)
块大小 64 Bytes ( 1 个 Cache Line 可存 8 个 double )
矩阵规模 A, B, C 均为 64×64 的方阵 (N=64)
存储方式 数组按行优先存储
内存对齐 A, B, C 的起始地址均对齐到 Cache 的起始 Set

代码实现

1
2
3
4
5
6
7
8
9
10
11
// 假设变量 sum 已优化到寄存器中,忽略 C 的访存影响
// 仅考虑内层循环中 A 和 B 的读取
for (int j = 0; j < 64; ++j) { // Loop 1
for (int i = 0; i < 64; ++i) { // Loop 2
double sum = 0.0;
for (int k = 0; k < 64; ++k) { // Loop 3
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}

问题 10.1

我们试图分析上述代码中最内层循环 Loop 3 对矩阵 的访存行为。

已知 Cache 总共有 个 Set 。

在计算
的过程中(即一次完整的 Loop 3 ),关于
的 Cache Miss Rate (不命中率),下列说法正确的是:

选项 描述
A 12.5% - 这里有良好的空间局部性,每 8 个 double 只有 1 次 Miss
B 25% - 虽然是列优先访问,但 Cache 够大,只有冷不命中
C 约 50% - A 和 B 互相打架(冲突),导致一半的数据被驱逐
D 100% - 发生了严重的 Cache Thrashing (抖动),每次读取都是 Miss

💡 提示:计算一下访问 时的内存地址差值( Stride ),以及它们映射到的 Set Index 的跨度。

正确答案是 D 。

解释如下:

  • 矩阵 B 是按行优先存储的,因此访问 B[k][j] 时, k 的变化会导致访问的内存地址以列为单位跳跃。

  • 计算地址差值( Stride ):

  • 每次访问 B[k][j] 时,地址增加 512 Bytes ,而每个 Cache Line 大小为 64 Bytes ,因此每次访问都会跨越多个 Cache Line 。

  • 计算 Set Index 的跨度:

  • 因为 Cache 有 64 个 Set ,跨度为 8 意味着每次访问都会映射到不同的 Set ,但由于 k 从 0 到 63 ,共有 64 次访问,这些访问会循环映射到同一组 Set 上,导致频繁的冲突和驱逐。

  • 最终结果是每次读取 B[k][j] 都会导致 Cache Miss ,即 Cache Thrashing 。

问题 10.2
为了进一步提升矩阵乘法的效率,我们决定使用分块技术。你将矩阵分成了 的小块( Block Size = 8 )。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 8x8 分块优化演示
for (int jj = 0; jj < 64; jj += 8) {
for (int ii = 0; ii < 64; ii += 8) {
for (int kk = 0; kk < 64; kk += 8) {
// 在这里处理 8x8 的子块乘法
for (int j = jj; j < jj + 8; ++j) {
for (int i = ii; i < ii + 8; ++i) {
double sum = C[i][j]; // 简化写法
for (int k = kk; k < kk + 8; ++k) {
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
}
}
}

针对一个 矩阵子块(假设该子块已预加载),在处理该子块内部的计算时,关于其在 L1 Cache 中的状态,下列分析正确的是:

选项 描述
A 一个 8×8 的子块大小为 512 Bytes ,远小于 Cache 大小,因此完全没有冲突,所有数据都能驻留在 Cache 中
B 尽管子块很小,但由于 B 的原始列宽( Stride )很大,导致子块内的 8 行数据全部映射到了同一个 Set 中,依然存在严重的冲突
C 子块内的 8 行数据分别映射到了 8 个不同的 Set 中( Set 索引间隔为 8 ),且在子块计算期间不会发生自我冲突( Self-Conflict )
D 分块主要是为了利用 L2/L3 Cache ,对这么小的 L1 Cache (4KB) 来说, 8×8 的分块没有任何意义

正确答案是 C 。

解释如下:

  • 一个 8×8 的子块大小为:

  • 该子块的大小( 512 Bytes )确实远小于 L1 Cache 大小( 4KB ),但关键在于访问模式。

  • 在处理该子块时,访问 B[k][j] 时, k 的变化会导致访问的内存地址以列为单位跳跃。

  • 计算 Set Index 的跨度:

  • 因此,子块内的 8 行数据分别映射到了 8 个不同的 Set 中,且在子块计算期间不会发生自我冲突( Self-Conflict )。

  • 分块技术有效地利用了 Cache 的空间局部性,减少了冲突,提高了数据的命中率。

C 题

SF3D 论文阅读记录

引言

mesh construction 是我刚刚开始了解的一个方向, 今天读了SF3D: Scene Fusion for 3D Reconstruction with Transformers这篇论文, 本文笔记记录用于后续翻阅学习。

读完这篇论文之后, 感觉 mesh reconstruction 与 point cloud reconstruction 还是有很大区别的, 尤其是这篇文章中引入的几个新的 mesh 专有的 module, 感觉要比 point cloud reconstruction 更加复杂一些.OK,
废话不多说, 直接进入正题.

Introduction

作者一上来就提出了几个 issue:
SF3D提出的问题

  1. Light bake-in: 现有的模型将光照信息直接 bake 到 texture 里, 使得生成的 mesh 难以利用, 而在 SF3D 中, 作者提出了使用 explicit illumination 和一个不同的使用 Spherical Gaussian 的 shading model 来解决这个问题(如上图第一行所示).
  2. Vertex Coloring: 现有的工作中, 生成的 vertex 的数量过多, 使得性能开销很大. 作者认为一个关键问题就是 UV unwrapping 的额外处理时间, 于是作者提出了一种 highly parallelizable fast box projection-based UV
    unwrapping method 来解决这个问题(如上图第二行所示), 这使得时间从 10-30s 减少到了 0.5s, 而且从图上来看, 细节比 baseline 的 TripoSR 的效果更好.
  3. Marching Cube Artifacts: feed-forward network 通常生成类似与 Triplane NeRFs 的体素网格, 然后使用 marching cube 来提取 mesh, 但是这种方法会引入一些 artifacts,
    作者提出了使用一个对高分辨率 Triplane 更有效的 architecture, 并且使用 DMTet 来对生成的 vetex diplacement 和 normal map 生成最终的 mesh, 这样可以有效减少 marching cube 引入的 artifacts(如上图第三行所示).
  4. Lack of Material Properties: 现有的工作生成的 mesh 在不同光照下都会看起来 dull, 这是因为缺乏 explicit 的 material properties.为解决这个问题, 作者预测了 non-spartially varying material properties
    (如上图第 4, 5 行所示).

通过以上的改进, SF3D 可以从单张图像生成高质量的 mesh, 且生成的 3D 资产体积小(1 MB)并且可以在 0.5s 内生成.

Method

为了解决上面提到的问题, 作者提出了 SF3D.

首先, SF3D 是在 TripoSR 的基础上进行改进的. TripoSR 训练了一个能够生成 Triplane 3D representation 的 transformer. 它使用 DINO encode image, 然后把 token 送入 transformer 中, transformer 输出一个分辨率的
triplane, 然后 triplane feature 之后被 decode 为 color 和渲染成标准 NeRF. TripoSR 只学到了 colors 并且不能处理反射等材质属性.

Overview

SF3D 的整体架构如下图所示:
SF3D架构图
可以看到, SF3D 由 5 个主要模块组成:

  1. Enhanced Transformer: 用于预测高分辨率的 triplane feature.
  2. Merterial Estimation: 用于预测材质属性.
  3. Illumination Modeling: 处理光照问题.
  4. Mesh extraction and refinement: 用于从 triplane 中提取 mesh 并进行细化.
  5. UV Unwrapping and Export: 产生 low-poly mesh 和 高分辨率 texture map.

Enhanced Transformer

为了生成高分辨率的 triplane feature, 作者对 TripoSR 的 transformer 进行了改进, 主要有以下几点:

  • 首先, 作者将 DINO 替换成了 DINOv2, 这样可以获得更好的 image feature.
  • 其次, 作者对 triplane 导致的 aliasing 问题进行了讨论
    aliasing问题
    如上图所示, 低分辨率的 triplane 会导致 aliasing 问题, 但是简单地提高 triplane 的分辨率会导致模型更复杂, 作者说, 他从 PointInfinity 中获得启发,
    (PointInfinity 提供了一个不需要计算 triplane 的 self-attention 的架构), 因此, 作者将分辨率提高到, 从而降低了走样.

Material Estimation

SF3D 输出了 metallic 和 roughness 两个材质属性. 论文中提到, 理想状况下, 人们希望材质属性是 spatially varying 的, 但是这样并不现实. 于是作者简化了这个问题, 为整个物体
预测这两个属性, 作者提到虽然这种非空间变化的材质属性通常适用于同质物体, 但是实际上能显著改善渲染效果.

为了实现这个预测, 作者引入了一个 Material net, 首先将图像通过 CLIP encoder 编码, 然后通过 2 个 MLP 预测 metallic 和 roughness.

Illumination Modeling

作者提出要显式 estimating 光照, 如果不这样做的话, 输出的 RGB 颜色会将光照信息 bake 进去, 使得生成的 mesh 难以利用. 为此, 作者提出了一个 Light net, estimate SG 光照. 因为 triplane encode 了场景的几何信息, 所以可以能够推断光照变化.

具体实现上, 作者使用 Transformer 输出的 分辨率的 triplane 作为输入, 使其通过 2 个 CNN 层, 接着进行 max pool,
最后通过一个 MLP 。 Light Net 输出 24 个 SG 的 grayscale amplitude values, 并使用 Softplus 以确保值为正数。这些 SG 的轴和锐度值保持固定, 其设置旨在覆盖整个球体。
利用这些振幅值, 作者实施了一种类似于 NeRD [4] 中使用的 deferred physically based rendering 方法.

此外, 作者的方法在训练阶段还引入了一个 lighting demodulation loss , 该损失函数旨在确保:一个具有 entirely white albedo 的物体上的光照,
能与输入图像的亮度紧密匹配。 lighting demodulation loss 强制学习到的光照与训练数据中观察到的光照条件保持一致.
这可以被视为一种 bias, 用于解决 appearance 和 shading 之间的 ambiguity.

Mesh Extraction and Refinement

为了从 triplane 中提取 mesh, 作者使用了 DMTet. 作者提出了两个 MLP head 来预测 vertex offsets 和 vertex normals. 这里受 MeshLRM 启发, 作者也单独使用了分离的 decoder MLP 来辅助这两个 head 的训练.
作者发现, vertex offset 能够反走样, 而 vertex normal 则能提升细节表现. 鉴于一开始 normal map 的预测不会太准确, 于是作者使用了 slerp 来稳定训练, 这是在一开始的 5K step 里发生.

然后引入了各种 loss 来训练这个 mesh extraction and refinement 模块:

  • $$\mathcal{L}_{\text{Nrmconsistency}}$$: 法线一致性损失
  • $$\mathcal{L}_{\text{Laplacian}}$$: Laplacian 平滑损失
  • $$\mathcal{L}_{\text{Offset}} = v_o^2$$: 顶点偏移正则化
  • $$\mathcal{L}_{\text{Nrmrepl}} = 1 - n \cdot \hat{n}$$: 法线复制损失
  • $$\mathcal{L}_{\text{Nrmsmooth}} = (\hat{n}(x) - \hat{n}(x + \epsilon))^2$$: 法线平滑损失

UV Unwrapping and Export

SF3D 模型的最终阶段是一个高效的导出流水线, 关键挑战在于传统 UV 展开的计算密集性, 这不符合快速生成的要求. 为此, 作者提出了一个基于立方体投影的展开方法. 该方法利用网格面法线独立决定投影方向, 实现了可并行化的展开过程.
具体实现上, 该方法执行 2D 三角形-三角形相交测试来处理 UV 图集中的遮挡, 并根据深度和接近度对相交面进行重新分配. 同时, 通过遵循径向 切线方向旋转 UV 岛以最小化阴影接缝. 接着, 通过 UV 展开将世界坐标和占用率烘焙到 UV 图集上
, 用于从 triplane 中查询反照率和表面法线. 为防止接缝伪影, 作者采用了一个迭代过程, 使用 部分卷积和最大池化来扩展 UV 边界, 确保纹理平滑向外混合.

之后, 作者将所有文件作为 glb 格式导出.

Overall Training and Loss Functions

由于直接在网格渲染任务上训练方法会产生不满意的结果, 作者首先在 NeRF 任务上进行了预训练. 完成预训练后, 模型过渡到网格训练,
将 NeRF 渲染替换为 differentiable mesh rendering 和基于 SG 的着色.

分步的损失函数如下所示:\begin{split}\mathcal{L}<em>{\rm render}&=\underbrace{ \lambda</em>{\rm MSE}}<em>{ 1 0}\mathcal{L}</em>{\rm MSE}+\underbrace{ \lambda_{\rm LPIPS}}<em>{ 2}\mathcal{L}</em>{\rm LPIPS}+\underbrace{\lambda_{ \rm Mask}}<em>{ 1 0}\mathcal{L}</em>{\rm Mask}\ \mathcal{L}<em>{\rm mesh}&=\underbrace{\lambda</em>{\rm Laplacian }}<em>{ 0.01}\mathcal{L}</em>{\rm Laplacian}+\underbrace{\lambda_{\rm Nrm Consistency}}<em>{ 0.001}\mathcal{L}</em>{\rm Nrm consistency}+\underbrace{\lambda_{\rm Offset}}<em>{ 0.1}\mathcal{L}</em>{\rm Offset}\ \mathcal{L}<em>{\rm shading}&=\underbrace{\lambda</em>{\rm Nrm repl}}<em>{ 0.2}\mathcal{L}</em>{\rm Nrm repl}\underbrace{\lambda_{\rm Nrm smooth}}<em>{ 0.02}\mathcal{L}</em>{\rm Nrm smooth}+\underbrace{\lambda_{\rm Demod}}<em>{ 0.01}\mathcal{L}</em>{\rm Demod}\end{split}
总损失为:

Results

作者在 GSO 和 OminiObject3D 数据集上对 SF3D 进行了评估. 结果如下图所示:
结果图
可以看到, SF3D 在视觉效果上明显优于其他方法, 并且在数值指标上也有显著提升.

在速度方面, 确实如作者所说, SF3D 的 UV 展开非常快, 只需 0.5s, 远快于其他方法的 10-30s.
速度对比

Conclusion

因此, 我似乎大致总结完了 SF3D 的主要结构, 从一张图像生成高质量的 mesh, 能不能对视频进行这样的操作呢? 我们看到这个任务里实际上用了大量生成的先验知识, 我在想一个完全
基于 image 的 3D reconstruction 方法, 能不能做到不依赖于这些先验知识?