Recap of the past 5 months and vision for the next 2

After leaving big tech I joined a math startup at the end of March. This turned out to be a rich learning experience, though the financial prospect is weak and I was persuaded to join a more traditional startup instead. Another thing I find annoying is that I cannot easily separate family related stressors from interfering with my work.

As I described earlier, my son has obnoxious personality issue. This has mitigated a lot over the months. I now ascribe that to a great extent to my wife’s high pressure control over him, maybe similar to what’s described in the movie “The graduate”. Still things like negligence of ipad/macbook charging can give me huge stress. This applies to my daughter as well.

Last night I realized that my son’s extracurricular activities have soared to 8 items. That’s way more than what I got when I was his age, basically 0-1. I tried to convince my wife that that’s too much, but she does not budge. On the other hand, I have an ex-colleague who is in rehabilitation due to mental health issue supposedly caused by his inattentive wife, who does not care at all about kids’ education and uses excuses like “cannot find a piano”, “no tennis lessons nearby”. I feel like in the opposite situation.

Back to my stay at the math company. There are more than a few red flags along the way.

The founders seem incapable to manage an ML team, so they relentlessly outsourced it to European old guys who had dubious track records such as papers in neuro-symbolic non-mainstream research, or pre-training experience in a 2nd tier old school big company. Worst of all is that these people in management positions are not shy about the fact that they are entitled to boss around, and voice highly subjective opinions in public to directly humiliate or contradict actual hands-on researchers, perhaps to assert their power in front of the founders.

At such a small scale as the company was, there is also factions and power struggle, though not in explicit terms. My manager wanted me to tell him every collaboration I engage with other managers. Even some relatively junior team mates tend to be somewhat self-serving and bossy.

In any case, all of this is behind me now. What I am really afraid is that my family struggle will continue to haunt me in my new startup job, and if I quit within 5 months again due to inability to handle the internal and external stress, I may become a true loser in the corporate world.

Adding to the domestic and workspace stress is my own internal physical stress, namely gastritis, which has been with me since time immemorial. My early quitting of math career, finance career can all be attributed to that. Any sip of coffee or carbonated drinks will trigger it, though the causal relation is hard to discover, at least by my body, since the erosion of mucosal lining is gradual but takes a long time to recover.

The only thing I can afford to lose now is my youthful health. It is meant to be squandered, and when another gastritis episode hits me, or flu contracted from my kids, I will bite the bullet and try even harder on my body. It is the only way to redeem my temporal existence. I am not yet sure if I need to pull late night coding sessions. At least my wife is against it. The hardest things are

  • Stop working after work.
  • Stay awake in the afternoon at work, which motivated me to buy a desk pillow, though whether I have the courage to use it at work remains to be seen; the effect is definitely positive: much clearer thoughts and better decision making.
  • Stay awake during commute: even with FSD this will be a problem.
  • Do dishes and other chores repeatedly thousand times a year without complaint, and with quality high enough to satisfy my wife.
  • Know when sickness hits me as early as possible, and rest and do whatever I can to stop it.
  • Don’t be a miser and spend money whenever it’s necessary. Sell some stocks to cover my financial difficulties. And stop the bad habit of recreational day-trading.

Then I have to deal with sporadic inter-kids fights that usually end up like my daughter crying that her brother took her stuff or beat her up, and ask me for justice. The best I can do is some symbolic spanks on his butt. This kind of vicious cycle will continue at least until he is 15.

Once I succeed above, aging parents may be the next batch of challenges to deal with.

Finally there is the drowsiness when I read anything technical, including blogs, papers. That’s another crucial reason I quit math then and now: the mind and the body resists high intensity intellectual activities. With 1 day away from the new chapter in my life, I am genuinely at a loss and needs God’s guidance to live a life of fulfillment. Perhaps my pessimism is to blame foremost. A tragic life filled with optimism is better than the opposite, and at the very least it uplifts people around me.

Posted in Uncategorized | Tagged , , , , | Leave a comment

Speculative Decoding Demystified

I thought I understood speculative decoding a long time ago. But there are nuances like rejection sampling, residual sampling, and bonus token that I completely missed.

After getting bad explanation from gemini pro, I found the following much more understandable gemini flash implementation that covers all the above concepts very well.

Note that the function finishes an entire rollout (via max_new_tokens), not just one iteration of decoding.

import torch
import torch.nn.functional as F
def speculative_decoding_with_rejection(small_model, big_model, tokenizer, prompt, K=5, max_new_tokens=50, temperature=1.0):
input_ids = tokenizer(prompt, return_tensors='pt')['input_ids'].to(small_model.device)
num_prompt_tokens = input_ids.size(1)
while input_ids.size(1) - num_prompt_tokens < max_new_tokens:
current_len = input_ids.size(1)
draft_ids = input_ids.clone()
small_probs_list = []
# 1. Draft K tokens stochastically from the small model
for _ in range(K):
with torch.no_grad():
logits = small_model(draft_ids).logits[:, -1, :] / temperature
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
draft_ids = torch.cat([draft_ids, next_token], dim=-1)
small_probs_list.append(probs)
# Shape: (K, vocab_size)
small_probs = torch.cat(small_probs_list, dim=0)
# 2. Parallel verification pass with the big model
with torch.no_grad():
big_logits = big_model(draft_ids).logits
# Extract distributions corresponding to the draft positions
# Slicing from current_len - 1 yields K + 1 distributions (K validation + 1 final bonus)
verification_logits = big_logits[0, current_len - 1 : , :] / temperature
verification_probs = F.softmax(verification_logits, dim=-1)
big_probs = verification_probs[:K, :] # Shape: (K, vocab_size)
final_bonus_prob = verification_probs[K, :] # Shape: (vocab_size,)
# 3. Rejection Sampling Verification Loop
accepted_count = 0
bonus_token = None
for i in range(K):
token_id = draft_ids[0, current_len + i]
p = big_probs[i, token_id].item()
q = small_probs[i, token_id].item()
# Acceptance condition
if torch.rand(1).item() <= min(1.0, p / q):
accepted_count += 1
else:
# Sample recovery token from the normalized positive residual distribution
residual = torch.clamp(big_probs[i] - small_probs[i], min=0.0)
bonus_token = torch.multinomial(residual, num_samples=1).unsqueeze(0)
break
# 4. If all K tokens pass verification, sample the bonus token from the final distribution
if bonus_token == None:
bonus_token = torch.multinomial(final_bonus_prob, num_samples=1).unsqueeze(0)
# Update the sequence trajectory
accepted_tokens = draft_ids[:, current_len : current_len + accepted_count]
input_ids = torch.cat([input_ids, accepted_tokens, bonus_token], dim=-1)
return tokenizer.decode(input_ids[0], skip_special_tokens=True)
Posted in Uncategorized | Leave a comment

[I have tried my best] Son has obnoxious personality

I have honestly tried my best, but it feels like I’m pouring effort into a void. It’s hard not to feel the weight of it when my daughter is so naturally appreciative, while my son seems to bite the hand that feeds him. My wife has put three years of effort into his rock climbing, yet we’re met with constant whining in the car about whatever he doesn’t have in that moment. It’s deeply demoralizing. We’ve reached a point where it feels like the only way to save our own sanity is to just let him play his games until he’s eighteen and then move on. It feels like he’s a lost cause.

The feedback loop is fundamentally broken. I’ve told him at least 350 times not to stomp on the stairs, and it just never lands. It’s nearly impossible to create a meaningful reinforcement learning environment for him when the school’s own policies act as a safety net; if he forgets his lunch, they insist we bring it to him, so he never actually feels the consequence of his own negligence. He doesn’t learn because the world won’t let him.

Then there’s this “celebrity burden” the therapist mentioned. He’s pathologically obsessed with how others see him, to the point where he’s ashamed of us. He’ll push us out the door because he’s embarrassed by his grandmother’s English or even just our presence. The therapist says there’s no cure, only the hope that he eventually realizes no one is actually watching him as closely as he thinks they are. But even with that supposed sensitivity, he has zero empathy for the people right in front of him. Even when I’m sick and explicitly asking for isolation, he’s right there, demanding I look at his computer screen. It’s a lonely, exhausting cycle when a child yearns for attention so badly but can’t see the person he’s taking it from.

Posted in Uncategorized | Leave a comment

[popular science] How to explain the twin paradox like a real Renaissance man

Repeatedly I hear about time dilation or space dilation in science fictions or popular blogs, with respect to traveling near the speed of light of course. Here is a much more straightforward way to explain the twin paradox, rooted in common sense, that my averagely intelligent 11 year old can understand.

Imagine you are traveling from Earth to Tau Ceti, which is 12 light years away. Einstein would tell you it will take at least 12 years to get there right? Wrong! That’s just common sense, if you accelerate fast enough, you can get there in 1 nanosecond for Christ’s sake: just takes a lot of energy to reach that kind of acceleration.

So what’s up with your kids getting older than you by the time you come back to earth? Well, when your kid on earth observes you traveling to Tau Ceti, the fastest he can see is that you are traveling at a speed slightly lower than speed of light (c), according to the law that nothing can be faster than c. So then by elementary school mathematics, 12 light years \times 2 / speed of light = 24. So your kid will have aged at least 24 years while you aged by 1 nanosecond.

Posted in Uncategorized | Leave a comment

[I have done my best] Kids waste food

Today I will start a new series called “I have done my best”. It’s an act of desperation to vent some episodes in life I have no control over.

Today’s subject is around food waste. Both of my kids always leave about 1/4-1/2 of food in their bowls. The Chinese tradition says such habit may lead to hunger later in life. To me it’s a mental torture since I hate waste. Now imagine living with such creatures for 2 decades. I guess it originated from their mother who also always leaves a layer of rice at the bottom of her bowl at the end of every meal. She may be improving but the kids certainly aren’t. Breakfast today consisted of dumplings, which to me are pretty treasured meal. Still a total of 5 dumplings are left.

Verbal education has been applied repeatedly in the past. They will not heed it. I didn’t want to elevate it to carrot and stick level, since the cost of the waste is not worth any tangible monetary reward, I also want to reserve corporeal punishment for more urgent occasions.

Posted in Uncategorized | Leave a comment

Restoring macOS Option+Backspace Filename Component Deletion in VS Code Remote Terminals

When you SSH into a remote devserver via VS Code’s integrated terminal on macOS, you might expect Option+Backspace (⌥⌫) to delete back to the previous path separator (/), just like Finder’s “delete by component.” Instead, the default behavior often wipes the entire word up to the last space, which can be frustrating when working with long file paths.

This post walks through a simple, two‑step fix you can apply on any Mac + VS Code → remote‑bash setup to restore the familiar “kill until slash” behavior.


1. Make VS Code send Meta+DEL (ESC DEL)

By default, VS Code’s integrated terminal on macOS doesn’t treat Option as the Meta key. We’ll tell it to:

  1. Enable Option as Meta
    • Open your User Settings JSON (⇧⌘P → Preferences: Open Settings (JSON)) and add: { "terminal.integrated.macOptionIsMeta": true }
  2. Bind Option+Backspace to send ESC DEL
    • Open your Keybindings JSON (⇧⌘P → Preferences: Open Keyboard Shortcuts (JSON)) and insert: [ { "key": "alt+backspace", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\u001b\u007f" }, "when": "terminalFocus" } ]
    • Save and reload the window (Developer: Reload Window) if needed.

This ensures that whenever you press ⌥⌫ in the integrated terminal, VS Code emits the two‑byte sequence ESC (\u001b) followed by DEL (\u007f), which most shells interpret as Meta+DEL.


2. Teach Bash to kill until the previous slash

On the remote devserver (where your shell actually runs), Bash’s Readline by default treats Meta+DEL as backward-kill-word, which stops at whitespace. We’ll rebind it to unix-filename-rubout, which deletes back to the last /.

  1. Edit ~/.inputrc on the server (create it if missing):

    # Treat these characters as word separators for deletion and navigation
    set word-delimiters ” /_-.@:”
    # Bind Alt+Backspace to delete a word backward
    “\e\x7f”: backward-kill-word

    # Save changes and reload the settings
    bind -f ~/.inputrc
    
  2. Reload your Readline settings: bind -f ~/.inputrc # or just start a new login shell

After this, pressing ⌥⌫ will remove only the last path component:

$ echo /some/long/path/to/project/src
           ^ cursor here
# ⌥⌫ -> deletes "src" only, leaving: /some/long/path/to/project/


3. Quick Verification

If you ever want to confirm VS Code is sending the right bytes:

# On the remote
stty raw -echo
cat -v
# Press ⌥⌫ → you should see: ^[^?
# Then Ctrl+C and:
stty sane

And you can check Bash’s binding with:

bind -P | grep unix-filename-rubout
# should output: "\\e\\177": unix-filename-rubout


Conclusion

With just these two tweaks—local VS Code keybinding + remote Bash Readline rebind—you’ll have consistent macOS‑style “delete by filename component” behavior across any VS Code → SSH terminal session. Copy these steps to any new devserver, and avoid accidentally glob‑deleting entire directory names when you only meant to remove a segment.

Happy hacking!

Posted in Uncategorized | Leave a comment

Some triton debugging

Lately my job demanded some ever more in-depth understanding of triton-language, which is a python wrapper around cuda C.

One thing that took me a while to figure out was why forward pass of a torch Module worked fine, but in the backward pass I got illegal cuda memory address error.

It turns out for torch.view-like operations, such as torch.transpose, the underlying data doesn’t change (to save memcpy operations), but later slicing or other operations that depend on the contiguity of the input tensor may be unaware of this cost saving antecedent, hence attempting to access out of bound memory regions. In this case, the forward pass can ignore the out of bound memory access since it’s just a read operation. But during backward pass, out of bound access requires writing to illegal region of the memory, thus causing the above error.

In the flash attention triton kernel, there are several parameters that one can tune, namely, num_stages, BLOCKS_M, BLOCKS_N, and num_warps. The documentation for these parameters are lacking.

num_stages refer to the depth of asynchronous copy operations in the CUDA pipeline: fortunately the triton author explained this here.

BLOCKS_M and BLOCKS_N refer to the query vs key/value length block sizes. Thus if your d_model (embedding dimension going into the attention function) is very large, these need to be smaller to fit in the SRAM (shared memory?)

Finally num_warps control the number of threads working in parallel at any given point of time. If too small, there won’t be enough parallelism. If too large, it can take up resource for other operations besides the flash attention kernel to run at the same time.

Posted in Uncategorized | Leave a comment

Why the following 3sum closest solution does not work?

class Solution {
public:
    void twoSumClosest(vector<int>& nums, int target, int end, int offset, int& s, int& d) {
        int i = 0;
        int j = end;
        while (i < j) {
            int ret = nums[i] + nums[j] + offset;
            int dist = abs(target - ret);
            if (ret == target) {
                s = ret;
                d = 0;
                return;
            }
            if (d == -1 || dist < d) {
                d = dist;
                s = ret;
            }            
            if (ret < target) {
                ++i;
            } else {
                --j;
            }
        }
    }

    int threeSumClosest(vector<int>& nums, int target, int left, int right) {
        int s;
        int d = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            twoSumClosest(nums, target, mid - 1, nums[mid], s, d);
            if (d == -1 || s < target) {
                left = mid + 1;
            } else if (s == target) {
                return target;
            } else {
                right = mid - 1;
            }
        }
        return s;
    }

    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());        
        return threeSumClosest(nums, target, 0, nums.size() - 1);
    }
};

The idea above is to first sort the array, then do binary search on the first number, and find the closest 2sum in the complement. We keep track of the sum s and distance d.

It turns out I cannot even do a single outer layer binary search. The reason is that the condition

if (d == -1 || s < target) {
// or not

is not sufficient to inform that

left = mid + 1;
// or right = mid - 1;

if the realized sum s is < target, it is tempting to think the best first number should be somewhere to the right of existing chosen one (mid), but it is quite possible that it is to the left: the remaining two numbers just might need to be larger to compensate for it.

So it seems brute force search of the first number is the only option. One interesting thought. Since the above wrong solution passed 88 out of 99 unit tests, it seems interesting to come up with wrong solutions that pass all leetcode tests, and perhaps in the future that pass Generative AI logical reasoning. This could hopefully advance AGI.

class Solution {
public:
    void twoSumClosest(vector<int>& nums, int target, int start, int offset, int& s, int& d) {
        int i = start;
        int j = nums.size() - 1;
        while (i < j) {
            int ret = nums[i] + nums[j] + offset;
            int dist = abs(target - ret);
            if (ret == target) {
                s = ret;
                d = 0;
                return;
            }
            if (d == -1 || dist < d) {
                d = dist;
                s = ret;
            }            
            if (ret < target) {
                ++i;
            } else {
                --j;
            }
        }
    }

    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());     
        int s = 0, d = -1;
        for (int i = 0; i < nums.size() - 2; ++i) {
            twoSumClosest(nums, target, i + 1, nums[i], s, d);
            if (d == 0) {
                return s;
            }
        }
        return s;
    }
};
Posted in Uncategorized | Leave a comment

Consider joining xAI

I am a bit slow in following the news despite wasting no toothbrushing/driving time to watch youtube channels. One of my biggest idols since joining the industry, Christian Szegedy, recently moved from the google to the company that seeks to understand the universe. While I enjoy reading Roger Penrose’s Road to Reality, a complete guide to the laws of the universe, I never imagined myself in a similar position.

After reading the job posting, however, I realized math figured prominently in their mission. That’s not surprising. Christian has been pursuing automated theorem proving (for lack of a more professional term that I can never remember), ever since his Batch Normalization and CNN fame. In science, accessible work tends to attract more citations. But it’s the neural theorem proving stuff that attracted my attention.

Now there are many concerns about whether I can pass the interview let alone be competent at the position. I boasted the ambition to contribute to the LEAN theorem prover code base but never managed. My academic track record is meager.

I do have some strengths, including fast and meticulous execution of machine learning pipeline. I have a knack for formulating math problems out of industry problems, and combine branches of applied math to impress the reviewers. I can hardly think of much else these days. To maintain both skill excellence and work/life balance with kids seems impossible. Taking vitamin pills may help but it may take some time, especially needs to withstand the test of the upcoming winter chills.

But anyway I have accepted the offer for a verbal exchange in the coming week. Success lies in the ones who prepare as evidenced by my recent launch review encounter. Best form of preparation may be in the form of writing blog posts since I get disproportionately trained in input but hardly any output, especially outside the coding sphere.

One thing I may propose to Musk, if I get the chance, is to build some tool to facilitate the understanding of scientific literature, in the form of an IDE. I think that’s what Christian had in mind as well. He firmly believes in a rigorous framework for proof validation, before or one step ahead of neural onslaught. If there is a viable place for me to contribute to that ambition, I am all for it, while my youthful idealism lasts.

Lastly a shoutout to my wife for being super supportive of my financially downhill proposition. She comforted me by saying we spend way below our income level. But we all know it’s not just about current spending level but psychological security. It’s a sacrifice that she may not realize the gravity of. But it’s blessing to be surrounded by idealist like her, no matter how uninformed it might be.

Posted in Uncategorized | Leave a comment

Gumbel Softmax is basically TopK with some noise

I have been mystified by the notion of Gumbel Softmax. Even though the idea is very simple (we add Gumbel noise to make top k equivalent to sampling without replacement), papers and blogs make it appear very theoretical, and it’s hard to connect it to actual implementation.

So I decide to write this short note to help people similarly frustrated and in need of a quick refresher.

First, the major advertised appeal of Gumbel Softmax is the fact that it allows back-propagation in a seemingly non-differentiable operation, that is sampling. But really there is nothing miraculous here. The top-k operation is similarly non-differentiable. However we can do something called pass-through differentiation to make it so:

\frac{\partial}{\partial t} \max (\{x_1(t), \ldots, x_n(t)\}) \approx \frac{\partial}{\partial t} x_j(t) \mid_{j = \arg\max_i\{x_i\}}

Here \max operator is the same as top-k for k = 1. The above equality is approximate because the \max operator is not differentiable when x_i = x_j for some i \neq j. However this happens also for ReLU and with zero probability at any given point in training, so we consider it a harmless approximation.

Next Gumbel Softmax is simply adding an i.i.d. Gumbel noise to each x_i above. By doing that, you achieve exact sampling according to the probability distribution given by a suitably normalized (x_1, \ldots, x_n). This is intuitively clear, since the higher x_i‘s will not be affected by the noise added as much as the lower x_i‘s, hence remains highly probable to be chosen by the top-k operation.

Posted in Uncategorized | Leave a comment