Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache tricks. #19

Merged
merged 1 commit into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Jjama3.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export TransformerBlock
export Transformer
export unrope
export rerope_cache!
export scrape_cache
export append_cache!

include("model.jl")
export forward_loss
Expand Down
20 changes: 20 additions & 0 deletions src/layers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,24 @@
unroped = unrope(oldrope, l.attention.cache.cache_k[:,range,:,:])
l.attention.cache.cache_k[:,range,:,:] .= newrope(unroped)
end
end

function scrape_cache(model::Transformer)
cache = (k = [], v = [])
for l in model.layers
push!(cache.k, copy(l.attention.cache.cache_k[:,1:model.pos,:,:]))
push!(cache.v, copy(l.attention.cache.cache_v[:,1:model.pos,:,:]))
end
return cache

Check warning on line 262 in src/layers.jl

View check run for this annotation

Codecov / codecov/patch

src/layers.jl#L256-L262

Added lines #L256 - L262 were not covered by tests
end

function append_cache!(model, cache)
if model.pos + size(cache.k[1], 2) > size(model.layers[1].attention.cache.cache_k, 2)
extend_cache!(model, model.pos + size(cache.k[1], 2))

Check warning on line 267 in src/layers.jl

View check run for this annotation

Codecov / codecov/patch

src/layers.jl#L265-L267

Added lines #L265 - L267 were not covered by tests
end
for (i, l) in enumerate(model.layers)
l.attention.cache.cache_k[:, model.pos+1:model.pos+size(cache.k[i], 2), :, :] .= cache.k[i]
l.attention.cache.cache_v[:, model.pos+1:model.pos+size(cache.v[i], 2), :, :] .= cache.v[i]
end
model.pos = model.pos + size(cache.k[1], 2)

Check warning on line 273 in src/layers.jl

View check run for this annotation

Codecov / codecov/patch

src/layers.jl#L269-L273

Added lines #L269 - L273 were not covered by tests
end
Loading