Hi Toby,

Thanks for replying

and good idea!

the attached patch (against R-devel r90842) adds predict(..., cache = TRUE)

on the span = 0.5 error, well, span was passed to predict(), which ignores it, 
so the fit still used 0.75. It needs to go to loess().

also, with or without the patch, the existing workspace limit stops se = TRUE 
at about N = 46,300 for span = 0.5 (37,800 for 0.75), so N has to stay below 
that

ares <- atime::atime(
  N = unique(as.integer(10^seq(1, log10(45000), by = 0.1))),
  setup = {
    set.seed(20261105)
    x <- runif(N, -3, 3)
    y <- sin(x) + rnorm(N, sd = 0.35)
    f <- loess(y ~ x, span = 0.5)
    nd <- data.frame(x = seq(min(x), max(x), length.out = 80L))
  },
  seconds.limit = 1,
  cache.FALSE = predict(f, nd, se = TRUE, cache = FALSE),
  cache.TRUE = predict(f, nd, se = TRUE, cache = TRUE))

in my run cache = FALSE hit the 1 s limit at N = 10,000, and both gave bit for 
bit identical predictions

the gap between the two memory curves is just the new table, which is now 
allocated with R_alloc as you suggested; the existing workspace still uses 
R_Calloc, which atime doesn't see

i guess the old search is probably what made predict(se = TRUE) grow with N^2. 
with cache = TRUE the time roughly doubles when N doubles (0.09 s to 0.17 s CPU 
from N = 20,000 to 40,000), while cache = FALSE roughly quadruples (1.1 s to 
4.4 s from 10,000 to 20,000), which fits the log-linear plot you got. what 
still grows with N^2 is the workspace, and that is what limits N

Thanks,
Don


________________________________________
From: Toby Hocking <[email protected]>
Sent: Friday, 06 November 2026 19:06:03
To: Dong Yin
Cc: [email protected]
Subject: Re: loess: repeated neighbour list search in ehg191 makes predict(se = 
TRUE) slow

also even better if the temporary arrays used the R memory allocation
(not fortran), so then we can compare the memory usage (fortran
allocations are not accounted for in the atime analysis)… is that
possible? (I’m not great at hacking fortran but I know that could work
with C)

On Fri, Nov 6, 2026 at 2:03 PM Toby Hocking <[email protected]> wrote:
>
> Thanks for the response Don. That is interesting.
> I tried the span=0.5 but still error on my end.
> Decreasing the atime seconds.limit from 1 to 0.1 gives an encouraging
> result which looks log linear though
> https://github.com/tdhock/atime/issues/135#issuecomment-6692949103
>
> The improvement would be more convincing if we could run the two
> versions side by side in the same R session.
> Can you make a patch with a new argument, like predict(cache=TRUE) for
> your new version and FALSE for the old version? That way we could run
> both in the same R session to more obviously see the improvements.
>
> On Thu, Nov 5, 2026 at 4:00 PM Dong Yin <[email protected]> wrote:
> >
> > Hi Toby and all,
> >
> > The list rejected my last message because of the images (again, sorry), so 
> > here it is again in text for everyone else. Toby, sorry for the duplicate.
> >
> > I don't think the error comes from the patch. Stock R 4.5.2 and the 
> > unpatched trunk sources stop with the same message, and the same number, at 
> > N = 39810:
> >
> > workspace required (2377642345) is too large probably because of setting 
> > 'se = TRUE'.
> >
> > With se = TRUE, loess needs a workspace of roughly (D + 1) x nf x N 
> > doubles, and with the default span = 0.75 that passes INT_MAX at about N = 
> > 37,800. Without the patch your atime run reaches the 1 second limit long 
> > before that, so it never gets there. That's also why I used span = 0.5 for 
> > my N = 40,000 timings.
> >
> > The patch itself only adds an integer array of nv x N, and nv is 9 here, so 
> > about 1.3 MB at N = 37,000.
> >
> > On the scaling: unpatched predict took 0.08, 1.1, 5.2 and 24.2 s for N = 
> > 5,000, 10,000, 20,000 and 40,000 at span = 0.5. So below 10,000 it is much 
> > steeper than quadratic for me too, then close to quadratic up to 40,000. 
> > I'm not sure yet where the extra at small N comes from.
--- a/src/library/stats/R/loess.R
+++ b/src/library/stats/R/loess.R
@@ -266,7 +266,8 @@
 }
 
 predict.loess <-
-    function(object, newdata = NULL, se = FALSE, na.action = na.pass, ...)
+    function(object, newdata = NULL, se = FALSE, na.action = na.pass,
+             cache = TRUE, ...)
 {
     if(!inherits(object, "loess"))
        stop("first argument must be a \"loess\" object")
@@ -284,7 +285,7 @@
                      op$span, op$degree, op$normalize,
                      op$parametric, op$drop.square, op$surface,
                      op$cell, op$family,
-                     object$ kd, object$ divisor, se = se)
+                     object$ kd, object$ divisor, se = se, cache = cache)
     if(!is.null(out.attrs <- attr(newdata, "out.attrs"))) { # expand.grid used
         if(se) {
             res$fit    <- array(res$fit,    out.attrs$dim, out.attrs$dimnames)
@@ -299,7 +300,7 @@
 predLoess <-
   function(y, x, newx, s, weights, robust, span, degree,
           normalize, parametric, drop.square, surface, cell, family,
-          kd, divisor, se = FALSE)
+          kd, divisor, se = FALSE, cache = TRUE)
 {
     ## translation of pred_
     D <- NCOL(x); N <- NROW(x); M <- NROW(newx)
@@ -399,7 +400,8 @@
                        as.integer(N),
                        as.integer(M1),
                        double(M1),
-                       L = double(N*M1)
+                       L = double(N*M1),
+                        as.integer(cache)
                        )$L
                tmp <- rowSums(matrix(L^2, M1, N) / rep(weights, rep_len(M1,N)))
                se.fit[inside] <- s * sqrt(tmp)
--- a/src/library/stats/src/loessc.c
+++ b/src/library/stats/src/loessc.c
@@ -65,7 +65,7 @@
 void F77_NAME(lowese)(int*, double*, int*, double*, double*);
 void F77_NAME(lowesf)(double*, double*, double*, int*, double*,
                      int*, double*, double*, int*, double*);
-void F77_NAME(lowesl)(int*, double*, int*, double*, double*);
+void F77_NAME(lowesl)(int*, double*, int*, double*, double*, int*, int*);
 void F77_NAME(ehg169)(int*, int*, int*, int*, int*, int*,
                      double*, int*, double*, int*, int*, int*);
 void F77_NAME(ehg196)(int*, int*, double*, double*);
@@ -151,10 +151,11 @@
        F77_CALL(lowesa)(trL, n, d, &tau, &nsing, one_delta, two_delta);
     }
     else if (!strcmp(*surf_stat, "interpolate/exact")) {
+        int cache = 0, inv = 0;
        hat_matrix = (double *) R_alloc((*n)*(*n), sizeof(double));
        LL = (double *) R_alloc((*n)*(*n), sizeof(double));
        F77_CALL(lowesb)(x, y, weights, diagonal, &one, iv, v);
-       F77_CALL(lowesl)(iv, v, n, x, hat_matrix);
+       F77_CALL(lowesl)(iv, v, n, x, hat_matrix, &cache, &inv);
        F77_CALL(lowesc)(n, hat_matrix, LL, trL, one_delta, two_delta);
        F77_CALL(lowese)(iv, v, n, x, surface);
        loess_prune(parameter, a, xi, vert, vval);
@@ -220,14 +221,18 @@
 loess_ise(double *y, double *x, double *x_evaluate, double *weights,
          double *span, int *degree, int *nonparametric,
          int *drop_square, int *sum_drop_sqr, double *cell,
-         int *d, int *n, int *m, double *fit, double *L)
+         int *d, int *n, int *m, double *fit, double *L, int *cache)
 {
     loess_workspace(*d, *n, *span, *degree, *nonparametric, drop_square, 
*sum_drop_sqr, TRUE);
 
-    int i0 = 0; double d0 = 0.0;
+    int i0 = 0, *inv = &i0;
+    double d0 = 0.0;
     v[1] = *cell;
     F77_CALL(lowesb)(x, y, weights, &d0, &i0, iv, v);
-    F77_CALL(lowesl)(iv, v, m, x_evaluate, L);
+    /* iv[5] is the actual number of vertices, set by lowesb(). */
+    if (*cache)
+       inv = (int *) R_alloc((size_t) iv[5] * *n, sizeof(int));
+    F77_CALL(lowesl)(iv, v, m, x_evaluate, L, cache, inv);
     loess_free();
 }
 
--- a/src/library/stats/src/loessf.f
+++ b/src/library/stats/src/loessf.f
@@ -777,17 +777,34 @@
       end
 
       subroutine ehg191(m,z,l,d,n,nf,nv,ncmax,vc,a,xi,lo,hi,c,v,nvmax,
-     +                  vval2,lf,lq)
+     +                  vval2,lf,lq,cache,inv)
 c Args
-      integer m,d,n,nf,nv,ncmax,nvmax,vc
+      integer m,d,n,nf,nv,ncmax,nvmax,vc,cache
+      integer inv(nv,n)
       double precision z(m,d), l(m,n), xi(ncmax), v(nvmax,d),
      +     vval2(0:d,nvmax), lf(0:d,nvmax,nf)
       integer lq(nvmax,nf),a(ncmax),c(vc,ncmax),lo(ncmax),hi(ncmax)
 c Var
       integer lq1,i,i1,i2,j,p
+      logical found
       double precision zi(8)
       double precision ehg128
       external ehg128
+
+c Inverse neighbour positions, using workspace allocated by the C caller.
+c Ascending p preserves the original search's last-match semantics.
+      if(cache.ne.0)then
+         do 20 j=1,n
+            do 21 i=1,nv
+               inv(i,j)=0
+   21       continue
+   20    continue
+         do 22 p=1,nf
+            do 23 i=1,nv
+               inv(i,lq(i,p))=p
+   23       continue
+   22    continue
+      end if
 
       do 3 j=1,n
          do 4 i2=1,nv
@@ -796,17 +813,23 @@
     5       continue
     4    continue
          do 6 i=1,nv
-c           linear search for i in Lq
-            lq1=lq(i,1)
-            lq(i,1)=j
-            p=nf
-c           top of while loop
-    7       if(.not.(lq(i,p).ne.j))goto 8
-               p=p-1
-               goto 7
-c           bottom of while loop
-    8       lq(i,1)=lq1
-            if(lq(i,p).eq.j)then
+            if(cache.ne.0)then
+               p=inv(i,j)
+               found=p.ne.0
+            else
+c              linear search for i in Lq
+               lq1=lq(i,1)
+               lq(i,1)=j
+               p=nf
+c              top of while loop
+    7          if(.not.(lq(i,p).ne.j))goto 8
+                  p=p-1
+                  goto 7
+c              bottom of while loop
+    8          lq(i,1)=lq1
+               found=lq(i,p).eq.j
+            end if
+            if(found)then
                do 9 i1=0,d
                   vval2(i1,i)=lf(i1,i,p)
     9          continue
@@ -1708,9 +1731,9 @@
 
 c Called either from loess_raw() only for case [surf_stat = 
"interpolate/exact"], or
 c               from loess_ise() {used only when 'se = TRUE' and surface = 
"interpolate"}
-      subroutine lowesl(iv,wv,m,z,l)
-      integer m
-      integer iv(*)
+      subroutine lowesl(iv,wv,m,z,l,cache,inv)
+      integer m,cache
+      integer iv(*),inv(*)
       double precision l(m,*), wv(*), z(m,1)
 
       external loesswarn,ehg191
@@ -1726,7 +1749,7 @@
       end if
       call ehg191(m,z,l,iv(2),iv(3),iv(19),iv(6),iv(17),iv(4),iv(iv(7)),
      +     wv(iv(12)),iv(iv(10)),iv(iv(9)),iv(iv(8)),wv(iv(11)),iv(14),
-     +     wv(iv(24)),wv(iv(34)),iv(iv(25)))
+     +     wv(iv(24)),wv(iv(34)),iv(iv(25)),cache,inv)
       return
       end
 
--- a/src/library/stats/src/modreg.h
+++ b/src/library/stats/src/modreg.h
@@ -56,7 +56,7 @@
 loess_ise(double *y, double *x, double *x_evaluate, double *weights,
          double *span, int *degree, int *nonparametric,
          int *drop_square, int *sum_drop_sqr, double *cell,
-         int *d, int *n, int *m, double *fit, double *L);
+         int *d, int *n, int *m, double *fit, double *L, int *cache);
 
 void kmeans_Lloyd(double *x, int *pn, int *pp, double *cen, int *pk, int *cl,
                  int *pmaxiter, int *nc, double *wss);
--- a/src/library/stats/src/init.c
+++ b/src/library/stats/src/init.c
@@ -33,7 +33,7 @@
     C_DEF(loess_dfit, 13),
     C_DEF(loess_dfitse, 16),
     C_DEF(loess_ifit, 8),
-    C_DEF(loess_ise, 15),
+    C_DEF(loess_ise, 16),
     C_DEF(multi_burg, 11),
     C_DEF(multi_yw, 10),
     C_DEF(HoltWinters, 17),
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to