"""Forward Qwen2 desde tensores GGUF dequantizados; prototipo no validado con Qwen."""
import math
import torch
import torch.nn.functional as F

def rms(x,weight,eps):
    return (x.float()*torch.rsqrt(x.float().square().mean(-1,keepdim=True)+eps)).to(x.dtype)*weight

def rope(x,positions,base):
    dim=x.shape[-1]
    inv=base**(-torch.arange(0,dim,2,device=x.device,dtype=torch.float32)/dim)
    theta=positions.float()[:,None]*inv[None,:]
    angles=torch.cat((theta,theta),dim=-1)
    a,b=x.chunk(2,dim=-1)
    rotated=torch.cat((-b,a),dim=-1)
    return x*angles.cos()[None,None,:,:].to(x.dtype)+rotated*angles.sin()[None,None,:,:].to(x.dtype)

class Cache:
    def __init__(self,layers,batch,kv_heads,capacity,head_dim,device,dtype):
        shape=(batch,kv_heads,capacity,head_dim)
        self.k=[torch.empty(shape,device=device,dtype=dtype) for _ in range(layers)]
        self.v=[torch.empty(shape,device=device,dtype=dtype) for _ in range(layers)]
        self.length=[0]*layers
    def append(self,layer,k,v,pos):
        assert pos==self.length[layer] and pos+k.shape[2]<=self.k[layer].shape[2]
        end=pos+k.shape[2];self.k[layer][:,:,pos:end]=k;self.v[layer][:,:,pos:end]=v
        self.length[layer]=end
        return self.k[layer][:,:,:end],self.v[layer][:,:,:end]

def forward(W,ids,layers,heads,kv_heads,eps,base,cache=None,pos=0,last_only=False):
    batch,length=ids.shape;d=W['token_embd.weight'].shape[1];head_dim=d//heads
    assert d%heads==0 and heads%kv_heads==0 and head_dim%2==0
    x=F.embedding(ids,W['token_embd.weight'])
    positions=torch.arange(pos,pos+length,device=ids.device)
    for layer in range(layers):
        p=f'blk.{layer}.';r=rms(x,W[p+'attn_norm.weight'],eps)
        def proj(name):return F.linear(r,W[p+'attn_'+name+'.weight'],W[p+'attn_'+name+'.bias'])
        q=proj('q').reshape(batch,length,heads,head_dim).transpose(1,2)
        k=proj('k').reshape(batch,length,kv_heads,head_dim).transpose(1,2)
        v=proj('v').reshape(batch,length,kv_heads,head_dim).transpose(1,2)
        q=rope(q,positions,base);k=rope(k,positions,base)
        if cache is not None:k,v=cache.append(layer,k,v,pos)
        else:assert pos==0
        k=k.repeat_interleave(heads//kv_heads,dim=1);v=v.repeat_interleave(heads//kv_heads,dim=1)
        allowed=torch.arange(k.shape[2],device=ids.device)[None,:] <= positions[:,None]
        a=F.scaled_dot_product_attention(q,k,v,attn_mask=allowed).transpose(1,2).reshape(batch,length,d)
        x=x+F.linear(a,W[p+'attn_output.weight'])
        h=rms(x,W[p+'ffn_norm.weight'],eps)
        x=x+F.linear(F.silu(F.linear(h,W[p+'ffn_gate.weight']))*F.linear(h,W[p+'ffn_up.weight']),W[p+'ffn_down.weight'])
    if last_only:x=x[:,-1:,:]
    return F.linear(rms(x,W['output_norm.weight'],eps),W['output.weight']).float()

def load_tensor(t,device='cuda',dtype=torch.float16,rows=256):
    import numpy as np
    from gguf.quants import dequantize
    shape=tuple(int(n) for n in reversed(t.shape))
    out=torch.empty(shape,device=device,dtype=dtype)
    for start in range(0,shape[0],rows):
        end=min(start+rows,shape[0])
        part=np.array(dequantize(t.data[start:end],t.tensor_type),copy=True,order='C')
        out[start:end]=torch.from_numpy(part).to(device=device,dtype=dtype)
    return out

def load_gguf(path,device='cuda',dtype=torch.float16):
    import gguf
    reader=gguf.GGUFReader(str(path));result={}
    for t in reader.tensors:
        if t.name.endswith('.weight') or t.name.endswith('.bias'):
            result[t.name]=load_tensor(t,device,dtype)
    return result

def selftest():
    torch.manual_seed(13);d=16;heads=4;kv=2;vocab=31;layers=2;mlp=32;hd=d//heads
    W={'token_embd.weight':torch.randn(vocab,d),'output.weight':torch.randn(vocab,d),'output_norm.weight':torch.ones(d)}
    for l in range(layers):
        p=f'blk.{l}.'
        W[p+'attn_norm.weight']=torch.ones(d);W[p+'ffn_norm.weight']=torch.ones(d)
        for name,n in [('q',d),('k',kv*hd),('v',kv*hd)]:
            W[p+'attn_'+name+'.weight']=torch.randn(n,d)/math.sqrt(d);W[p+'attn_'+name+'.bias']=torch.randn(n)/10
        W[p+'attn_output.weight']=torch.randn(d,d)/math.sqrt(d)
        W[p+'ffn_gate.weight']=torch.randn(mlp,d)/math.sqrt(d)
        W[p+'ffn_up.weight']=torch.randn(mlp,d)/math.sqrt(d)
        W[p+'ffn_down.weight']=torch.randn(d,mlp)/math.sqrt(mlp)
    ids=torch.tensor([[1,2,3,4,5],[7,8,9,10,11]])
    full=forward(W,ids,layers,heads,kv,1e-6,1e6)
    cache=Cache(layers,2,kv,5,hd,'cpu',torch.float32)
    parts=[forward(W,ids[:,i:i+1],layers,heads,kv,1e-6,1e6,cache,i) for i in range(5)]
    err=(full-torch.cat(parts,dim=1)).abs().max().item()
    assert err<1e-5,err
    assert cache.length==[5]*layers
    print('Prueba sintética de caché frente a prefijo completo:',err,flush=True)
if __name__=='__main__':selftest()
