|
1 | 1 | module TensorKitGPUArraysExt |
2 | 2 |
|
3 | 3 | using GPUArrays |
| 4 | +using LinearAlgebra: LinearAlgebra |
4 | 5 | using GPUArrays: @allowscalar |
5 | 6 | using GPUArrays.KernelAbstractions: @kernel, @index, get_backend |
6 | 7 | using Adapt |
@@ -666,6 +667,46 @@ TensorKit._transform_subblocks( |
666 | 667 | const GPUDiagonalTensorMap = DiagonalTensorMap{<:Any, <:Any, <:AnyGPUVector} |
667 | 668 | const GPUTensorMap = TensorMap{<:Any, <:Any, <:Any, <:Any, <:AnyGPUVector} |
668 | 669 |
|
| 670 | +# `norm` returns a host scalar by default, which forces the GPU to wait and synchronize. |
| 671 | +# Here we add some methods for various `p` that avoid copying back to the host if we |
| 672 | +# don't need to, e.g. for normalization. For the 2-norm, the norm is instead kept in a |
| 673 | +# 1-element device array and broadcast into the data. This matches the vendor device-side |
| 674 | +# nrm2 versions. |
| 675 | +function TensorKit._nrm2!(out::AnyGPUVector, x::AnyGPUArray) |
| 676 | + out .= sqrt.(vec(sum(abs2, x; dims = ntuple(identity, ndims(x))))) |
| 677 | + return out |
| 678 | +end |
| 679 | +TensorKit._nrm2!(out::AnyGPUVector, x::LinearAlgebra.Diagonal) = TensorKit._nrm2!(out, x.diag) |
| 680 | + |
| 681 | +function _device_norm2(t::Union{GPUTensorMap, GPUDiagonalTensorMap}) |
| 682 | + InnerProductStyle(t) === EuclideanInnerProduct() || TensorKit.throw_invalid_innerproduct(:norm) |
| 683 | + out = similar(t.data, float(real(scalartype(t))), 1) |
| 684 | + FusionStyle(sectortype(t)) isa UniqueFusion && return TensorKit._nrm2!(out, t.data) |
| 685 | + fill!(out, zero(eltype(out))) |
| 686 | + nb = similar(out) |
| 687 | + for (c, b) in blocks(t) |
| 688 | + out .+= dim(c) .* abs2.(TensorKit._nrm2!(nb, b)) |
| 689 | + end |
| 690 | + return out .= sqrt.(out) |
| 691 | +end |
| 692 | + |
| 693 | +function LinearAlgebra.normalize!(t::Union{GPUTensorMap, GPUDiagonalTensorMap}, p::Real = 2) |
| 694 | + p == 2 || return scale!(t, inv(norm(t, p))) |
| 695 | + t.data ./= _device_norm2(t) |
| 696 | + return t |
| 697 | +end |
| 698 | +function LinearAlgebra.normalize(t::Union{GPUTensorMap, GPUDiagonalTensorMap}, p::Real = 2) |
| 699 | + p == 2 || return scale(t, inv(norm(t, p))) |
| 700 | + tdst = similar(t, float(scalartype(t))) |
| 701 | + tdst.data .= t.data ./ _device_norm2(t) |
| 702 | + return tdst |
| 703 | +end |
| 704 | +function LinearAlgebra.normalize!(t::AdjointTensorMap{<:Any, <:Any, <:Any, <:Any, <:GPUTensorMap}, p::Real = 2) |
| 705 | + normalize!(parent(t), p) |
| 706 | + return t |
| 707 | +end |
| 708 | +LinearAlgebra.normalize(t::AdjointTensorMap{<:Any, <:Any, <:Any, <:Any, <:GPUTensorMap}, p::Real = 2) = adjoint(normalize(parent(t), p)) |
| 709 | + |
669 | 710 | # position of each subblock in the data of a `DiagonalTensorMap` in the same space |
670 | 711 | _diagonal_offsets(structure) = first(_work_offsets(first(first(s)) for s in structure)) |
671 | 712 |
|
|
0 commit comments