diff --git a/operator/CMakeLists.txt b/operator/CMakeLists.txt index d924c4c..f530a10 100644 --- a/operator/CMakeLists.txt +++ b/operator/CMakeLists.txt @@ -368,6 +368,20 @@ if(BUILD_TESTS) # Autograd engine tests if(USE_NEW_AUTOGRAD_ENGINE) + add_executable(test_reshape_autograd + finetune_ops/core/test_reshape_autograd.cpp + ) + target_link_libraries(test_reshape_autograd PRIVATE operators) + add_test(NAME ReshapeAutograd COMMAND test_reshape_autograd) + + add_executable(test_qwen_reshape_fd + finetune_ops/graph/test_qwen_reshape_fd.cpp + ) + target_link_libraries(test_qwen_reshape_fd PRIVATE operators) + add_test(NAME QwenReshapeFiniteDifference + COMMAND test_qwen_reshape_fd "${CMAKE_CURRENT_BINARY_DIR}/qwen_reshape_fd.csv" + ) + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../tests/test_autograd_engine.cpp) add_executable(test_autograd_engine ../tests/test_autograd_engine.cpp diff --git a/operator/finetune_ops/core/test_reshape_autograd.cpp b/operator/finetune_ops/core/test_reshape_autograd.cpp new file mode 100644 index 0000000..580d041 --- /dev/null +++ b/operator/finetune_ops/core/test_reshape_autograd.cpp @@ -0,0 +1,65 @@ +#include "finetune_ops/core/ops.h" +#include "finetune_ops/nn/lora_linear.h" +#include +#include +#include +#include +#include +#include +#include + +using namespace ops; +static int failures = 0; +static TensorPtr leaf() { + auto x = ones({2, 3}); + x->set_requires_grad(true); + return x; +} +static void check(const std::string& name, const TensorPtr& x, float expected) { + double error = 0; + const auto grad = x->grad(); + const bool layout_valid = grad && grad->shape() == x->shape() && grad->dtype() == x->dtype(); + if (layout_valid) for (int64_t i = 0; i < grad->numel(); ++i) + error = std::isfinite(grad->data()[i]) + ? std::max(error, double(std::abs(grad->data()[i] - expected))) + : std::numeric_limits::infinity(); + const bool pass = layout_valid && error < 1e-6; + failures += !pass; + std::cout << "{\"test\":\"" << name << "\",\"expected\":" << expected + << ",\"actual\":" << (layout_valid ? grad->data()[0] : -999) + << ",\"max_error\":" << error << ",\"passed\":" << (pass ? "true" : "false") << "}\n"; +} +static void run_ops() { + { auto x=leaf(); auto y=mul(x,1.0f); y->backward(ones(y->shape())); check("identity_op_control",x,1); } + { auto x=leaf(); auto y=x->reshape({3,2}); y->backward(ones(y->shape())); check("member_reshape",x,1); } + for (int depth=1; depth<=3; ++depth) { + auto x=leaf(), y=x; + for(int i=0;i{2,3}:std::vector{3,2}); + y->backward(ones(y->shape())); check("ops_reshape_depth_"+std::to_string(depth),x,1); + } + { auto x=leaf(); auto y=add(x,reshape(reshape(x,{3,2}),{2,3})); y->backward(ones(y->shape())); check("residual_two_reshapes",x,2); } + { auto x=leaf(); auto y=add(x,x); y->backward(ones(y->shape())); check("legitimate_repeated_input_add",x,2); } + { auto x=leaf(); auto y=mul(x,x); y->backward(ones(y->shape())); check("legitimate_repeated_input_mul",x,2); } + { auto x=leaf(); auto y=transpose(x,0,1); y->backward(ones(y->shape())); check("transpose_control",x,1); } + { auto x=leaf(); auto y=reshape(transpose(x,0,1),{6}); y->backward(ones(y->shape())); check("transpose_then_reshape",x,1); } + { auto x=ones({2,3}); auto y=reshape(x,{3,2}); bool pass=!y->requires_grad(); failures+=!pass; + std::cout << "{\"test\":\"frozen_input\",\"passed\":" << (pass?"true":"false") << "}\n"; } +} +static void run_lora(bool external_reshape) { + auto W=ones({3,2}); auto A=ones({3,2}); auto B=ones({2,2}); auto x=ones({1,2,3}); + LoRALinear layer(W); + layer.attach_lora(A,B,0.5f); + auto y=layer.forward(x); + if(external_reshape) y=reshape(y,{2,2}); + y->backward(ones(y->shape())); + // d sum(0.5 * X A B)/dA = 0.5 * X^T ones B^T = 2; + // d/dB = 0.5 * (X A)^T ones = 3. Independent analytic reference. + check(external_reshape ? "lora_plus_reshape_A" : "local_lora_A_control",A,2); + check(external_reshape ? "lora_plus_reshape_B" : "local_lora_B_control",B,3); +} +int main() { + std::cout << std::setprecision(10); + run_ops(); run_lora(false); run_lora(true); + std::cout << "{\"failures\":" << failures << "}\n"; + return failures ? 1 : 0; +} diff --git a/operator/finetune_ops/graph/test_qwen_reshape_fd.cpp b/operator/finetune_ops/graph/test_qwen_reshape_fd.cpp new file mode 100644 index 0000000..8760243 --- /dev/null +++ b/operator/finetune_ops/graph/test_qwen_reshape_fd.cpp @@ -0,0 +1,112 @@ +#include "finetune_ops/graph/qwen_model.h" +#include "finetune_ops/core/ops.h" +#include "finetune_ops/core/autograd_engine.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace ops; +static bool gradient_agrees(double grad, double fd) { + return std::isfinite(grad) && std::isfinite(fd) + && std::abs(grad-fd)<=0.0003+0.02*std::abs(fd); +} +int main(int argc, char** argv) { + if(argc!=2) throw std::runtime_error("Usage: qwen_fd output.csv"); + const double inf=std::numeric_limits::infinity(); + const double nan=std::numeric_limits::quiet_NaN(); + if(gradient_agrees(0.0,inf) || gradient_agrees(0.0,-inf) + || gradient_agrees(0.0,nan) || gradient_agrees(inf,inf) + || gradient_agrees(nan,0.0) || !gradient_agrees(0.0,0.0)) + throw std::runtime_error("Finite-difference comparison guard failed"); + QwenConfig cfg; + cfg.vocab_size=32; cfg.hidden_size=16; cfg.intermediate_size=32; + cfg.num_hidden_layers=2; cfg.num_attention_heads=4; cfg.num_key_value_heads=2; + cfg.head_dim=4; cfg.max_position_embeddings=32; + QwenModel model(cfg); + std::mt19937 rng(731); + std::normal_distribution random(0.0f, 0.1f); + auto assign=[&](const std::string& key, std::vector shape, bool norm=false) { + auto t=std::make_shared(shape,kFloat32,kCPU); + for(int64_t i=0;inumel();++i) t->data()[i]=(norm?1.0f:0.0f)+random(rng); + model.assign_weight(key,t); + }; + assign("embed_tokens.weight",{32,16}); assign("final_norm.weight",{16},true); + for(int layer=0;layer<2;++layer) { + const auto prefix="layers."+std::to_string(layer)+"."; + assign(prefix+"input_norm.weight",{16},true); assign(prefix+"post_norm.weight",{16},true); + for(const std::string target:{"q","k","v","o"}) { + const int dim=target=="k"||target=="v"?8:16; + assign(prefix+"self_attn."+target+"_proj.weight",{16,dim}); + if(target!="o") assign(prefix+"self_attn."+target+"_proj.bias",{dim}); + } + assign(prefix+"mlp.gate_proj.weight",{16,32}); assign(prefix+"mlp.up_proj.weight",{16,32}); + assign(prefix+"mlp.down_proj.weight",{32,16}); + } + model.init_lora(2,4.0f,0.0f,false); model.freeze_base(); + auto params=model.get_lora_parameters(); + if(params.size()!=16) throw std::runtime_error("Expected 16 LoRA tensors"); + for(auto& p:params) for(int64_t i=0;inumel();++i) p->data()[i]=random(rng); + auto ids=std::make_shared(std::vector{1,5},kInt32,kCPU); + for(int i=0;i<5;++i) ids->data()[i]=(i*5+2)%32; + auto weights=std::make_shared(std::vector{1,5,32},kFloat32,kCPU); + for(int64_t i=0;inumel();++i) weights->data()[i]=random(rng); + auto output=model.forward(ids); + if(output->shape()!=weights->shape()) throw std::runtime_error("Unexpected logits shape"); + auto value=[&](const TensorPtr& t) { + double acc=0; + for(int64_t i=0;inumel();++i) acc+=double(t->data()[i])*weights->data()[i]; + return acc; + }; + const auto objective=value(output); + std::ofstream forward(std::string(argv[1])+".forward.csv"); + if(!forward) throw std::runtime_error("Cannot open forward CSV output"); + forward << "element,logit\n" << std::setprecision(12); + for(int64_t i=0;inumel();++i) forward << i << ',' << output->data()[i] << '\n'; + // VJP seed corresponds exactly to the independent scalar dot product above. + output->backward(weights); + std::vector> grads; + for(auto& p:params) { + if(!p->grad()) throw std::runtime_error("Missing LoRA gradient"); + if(p->grad()->shape()!=p->shape() || p->grad()->dtype()!=kFloat32) + throw std::runtime_error("LoRA gradient layout mismatch"); + grads.emplace_back(p->grad()->data(),p->grad()->data()+p->numel()); + } + auto& engine=autograd::Engine::instance(); + engine.clear_graph(); engine.set_enabled(false); + std::ofstream out(argv[1]); + if(!out) throw std::runtime_error("Cannot open CSV output"); + out << std::setprecision(12) << "tensor,element,autograd,fd_eps_0.01,fd_eps_0.005\n"; + int count=0, failures=0; double error_max=0, fd_disagreement_max=0; + for(size_t k=0;knumel();++i) { + float& x=params[k]->data()[i]; const float old=x; + double fds[2]; int index=0; + for(float eps:{0.01f,0.005f}) { + x=old+eps; const double upper=value(model.forward(ids)); + x=old-eps; const double lower=value(model.forward(ids)); + x=old; fds[index++]=(upper-lower)/(2.0*eps); + } + const auto grad=grads[k][i]; + bool pass=std::isfinite(grad); + for(double fd:fds) pass=pass && gradient_agrees(grad,fd); + failures+=!pass; ++count; + error_max=std::max(error_max,std::abs(grad-fds[1])); + fd_disagreement_max=std::max(fd_disagreement_max,std::abs(fds[0]-fds[1])); + out << k << ',' << i << ',' << grad << ',' << fds[0] << ',' << fds[1] << '\n'; + } + } + engine.set_enabled(true); engine.clear_graph(); + if(count!=448) throw std::runtime_error("Expected 448 finite-difference elements"); + std::cout << std::setprecision(12) << "{\"objective\":" << objective + << ",\"gradient_entries\":" << count << ",\"failures\":" << failures + << ",\"max_abs_error_fd_0.005\":" << error_max + << ",\"fd_disagreement_max\":" << fd_disagreement_max << "}\n"; + return failures?1:0; +}