```python
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

_cpp_source = r"""
#include <torch/extension.h>

torch::Tensor triplet_margin_cuda(
    torch::Tensor anchor,
    torch::Tensor positive,
    torch::Tensor negative,
    double margin);
"""

_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <cstdint>
#include <cmath>

constexpr int THREADS = 256;

__device__ __forceinline__ float warp_sum(float value) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        value += __shfl_down_sync(0xffffffff, value, offset);
    return value;
}

__device__ __forceinline__ void accumulate(
    float a, float p, float n, float& positive_sum, float& negative_sum) {
    float dp = (a - p) + 1.0e-6f;
    float dn = (a - n) + 1.0e-6f;
    positive_sum = fmaf(dp, dp, positive_sum);
    negative_sum = fmaf(dn, dn, negative_sum);
}

template<bool VECTORIZED>
__global__ void triplet_rows(
    const float* __restrict__ anchor,
    const float* __restrict__ positive,
    const float* __restrict__ negative,
    float* __restrict__ losses,
    int64_t features,
    float margin) {

    const int tid = threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int64_t base = static_cast<int64_t>(blockIdx.x) * features;

    float sp = 0.0f;
    float sn = 0.0f;

    if (VECTORIZED) {
        const float4* a = reinterpret_cast<const float4*>(anchor + base);
        const float4* p = reinterpret_cast<const float4*>(positive + base);
        const float4* n = reinterpret_cast<const float4*>(negative + base);

        for (int64_t j = tid; j < features / 4; j += THREADS) {
            float4 av = a[j];
            float4 pv = p[j];
            float4 nv = n[j];
            accumulate(av.x, pv.x, nv.x, sp, sn);
            accumulate(av.y, pv.y, nv.y, sp, sn);
            accumulate(av.z, pv.z, nv.z, sp, sn);
            accumulate(av.w, pv.w, nv.w, sp, sn);
        }
    } else {
        for (int64_t j = tid; j < features; j += THREADS) {
            accumulate(anchor[base + j], positive[base + j],
                       negative[base + j], sp, sn);
        }
    }

    sp = warp_sum(sp);
    sn = warp_sum(sn);

    __shared__ float positive_partial[THREADS / 32];
    __shared__ float negative_partial[THREADS / 32];

    if (lane == 0) {
        positive_partial[warp] = sp;
        negative_partial[warp] = sn;
    }
    __syncthreads();

    if (warp == 0) {
        sp = lane < THREADS / 32 ? positive_partial[lane] : 0.0f;
        sn = lane < THREADS / 32 ? negative_partial[lane] : 0.0f;
        sp = warp_sum(sp);
        sn = warp_sum(sn);

        if (lane == 0) {
            float loss = (margin + sqrtf(sp)) - sqrtf(sn);
            losses[blockIdx.x] = loss < 0.0f ? 0.0f : loss;
        }
    }
}

__global__ void mean_loss(
    const float* __restrict__ losses,
    float* __restrict__ output,
    int64_t count) {

    float sum = 0.0f;
    for (int64_t i = threadIdx.x; i < count; i += THREADS)
        sum += losses[i];

    sum = warp_sum(sum);

    __shared__ float partial[THREADS / 32];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

    if (lane == 0)
        partial[warp] = sum;
    __syncthreads();

    if (warp == 0) {
        sum = lane < THREADS / 32 ? partial[lane] : 0.0f;
        sum = warp_sum(sum);
        if (lane == 0)
            output[0] = count ? sum / static_cast<float>(count) : NAN;
    }
}

torch::Tensor triplet_margin_cuda(
    torch::Tensor anchor,
    torch::Tensor positive,
    torch::Tensor negative,
    double margin) {

    TORCH_CHECK(anchor.is_cuda() && positive.is_cuda() && negative.is_cuda(),
                "Inputs must be CUDA tensors");
    TORCH_CHECK(anchor.device() == positive.device() &&
                anchor.device() == negative.device(),
                "Inputs must be on the same CUDA device");
    TORCH_CHECK(anchor.scalar_type() == at::kFloat &&
                positive.scalar_type() == at::kFloat &&
                negative.scalar_type() == at::kFloat,
                "Custom kernel requires float32 inputs");
    TORCH_CHECK(anchor.dim() == 2 &&
                anchor.sizes() == positive.sizes() &&
                anchor.sizes() == negative.sizes(),
                "Inputs must have matching [batch, features] shapes");

    const c10::cuda::CUDAGuard guard(anchor.device());

    anchor = anchor.contiguous();
    positive = positive.contiguous();
    negative = negative.contiguous();

    const int64_t batch = anchor.size(0);
    const int64_t features = anchor.size(1);

    auto losses = torch::empty({batch}, anchor.options());
    auto output = torch::empty({}, anchor.options());

    const float* a = anchor.data_ptr<float>();
    const float* p = positive.data_ptr<float>();
    const float* n = negative.data_ptr<float>();

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if (batch > 0) {
        const bool vectorized =
            features % 4 == 0 &&
            reinterpret_cast<uintptr_t>(a) % 16 == 0 &&
            reinterpret_cast<uintptr_t>(p) % 16 == 0 &&
            reinterpret_cast<uintptr_t>(n) % 16 == 0;

        if (vectorized) {
            triplet_rows<true><<<batch, THREADS, 0, stream>>>(
                a, p, n, losses.data_ptr<float>(),
                features, static_cast<float>(margin));
        } else {
            triplet_rows<false><<<batch, THREADS, 0, stream>>>(
                a, p, n, losses.data_ptr<float>(),
                features, static_cast<float>(margin));
        }
        C10_CUDA_KERNEL_LAUNCH_CHECK();
    }

    mean_loss<<<1, THREADS, 0, stream>>>(
        losses.data_ptr<float>(), output.data_ptr<float>(), batch);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return output;
}
"""

_triplet_extension = load_inline(
    name="fused_triplet_margin_cuda",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["triplet_margin_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, margin=1.0):
        super().__init__()
        self.margin = float(margin)
        self.loss_fn = nn.TripletMarginLoss(margin=margin)

    def forward(self, anchor, positive, negative):
        use_custom = (
            anchor.is_cuda
            and positive.is_cuda
            and negative.is_cuda
            and anchor.dtype == torch.float32
            and positive.dtype == torch.float32
            and negative.dtype == torch.float32
            and anchor.ndim == 2
            and anchor.shape == positive.shape == negative.shape
            and not (
                torch.is_grad_enabled()
                and (
                    anchor.requires_grad
                    or positive.requires_grad
                    or negative.requires_grad
                )
            )
        )
        if use_custom:
            return _triplet_extension.triplet_margin_cuda(
                anchor, positive, negative, self.margin
            )
        return self.loss_fn(anchor, positive, negative)
```