Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • ctools: a ton of really, really fast implementations for common Stata commands

    Dear Statalisters,

    I've released a package called ctools. ctools is a suite of drop-in replacements for a bunch of existing Stata commands (both built-in and user-written), but in general these commands are much, much faster than the programs they replace. The syntax for ctools mostly matches the commands they replace, and the name usually just gets a "c" in front: -cimport-, -cmerge-, -csort-, -creghdfe-, etc. In a handful of cases these commands offer some extended functionality, or combine the functionality of multiple commands. For instance, -cbinscatter- can use the covariate adjustment approach from Cattaneo et al.'s -binsreg- instead of residualizing x and y first, and it also has some stuff from my own -binscatter2-. -cinterpolate- does both linear interpolation like -ipolate- and cubic interpolation like Nick Cox's -cipolate- (ok, this one was hard to replace), etc.

    I am maintaining ctools on GitHub, and the repo has a variety of documentation (and of course the source code). The GitHub repository is here: https://www.github.com/mdroste/stata-ctools This repository has actually quietly been public for almost a year, but I don't care much for advertising my work and only a few people noticed. So we can call this Statalist post the 'public' release, although technically it's been available for most of this year and in fact has been on ssc for a month or so. I waited until I felt quite confident that the existing commands are fairly well-optimized, full-featured, and behave essentially identically to the commands they are based on.

    ctools works with Stata 14.1 or later on Windows (10 or later), Mac (Apple Silicon or Intel, macOS 11 or later), and x86-64 Linux.

    The latest version of ctools will always be available on my GitHub (above), and will be intermittently updated on SSC (I don't want to pester Kit too much every time something gets tweaked, this guy already does enough for this community!)

    Install from my GitHub (latest version):
    Code:
    net install ctools, from("https://raw.githubusercontent.com/mdroste/stata-ctools/main/build") replace
    Install from SSC (a little behind latest):
    Code:
    ssc install ctools, replace
    At the end of 2026 it should not be surprising, but almost all of the code for this project was written by AI. I mostly ran prompts on my phone at 11PM while watching The Sopranos and such (example prompts: (1) "please claude just make it run faster!!!" (2) "keep going i believe in you!!"). 98% of the total time was spent extensively building out validation, test harnesses, bug searches, etcetera. What makes this "work" is that whatever command you want to speed up can serve as an "oracle", and at this point coding agents/harnesses are quite good at reverse engineering the functionality (even if they don't have access to the source code, like some of the native Stata commands) of a program and porting the key bits to C. At this point I am reasonably confident that all these commands are about as fast as they could theoretically be and also free of bugs in nearly all use cases.

    It is a little hard to tell you exactly how much faster ctools will be than the commands they replace, because this depends a lot on your data and your machine (primarily your CPU and memory bandwidth). As a rough rule of thumb, commands which require moving more of your dataset will be relatively less fast, and commands which involve very high observation counts (e.g. tens of millions or more) will be relatively more fast. Regressions (in my experience) often don't involve more than a dozen or so variables, so they hold up well. You can see the rough speedups on the GitHub, but broadly speaking most of these commands will run something like 2 to 50 times faster than the programs they replace (sometimes more).

    Here are some of the included ctools commands and what they replace:
    Code:
    Command                   ctools version      
    -----------------------------------------------------
    Built-in commands
      import                  cimport              
      export                  cexport              
      sort                    csort              
      merge                   cmerge        
      sample                  csample          
      bsample                 cbsample        
      encode                  cencode      
      decode                  cdecode      
      destring                cdestring    
      ipolate                 cinterpolate  
      split                   csplit              
      qreg                    cqreg      
    
    User-written commands
      distinct                cdistinct          
      rangejoin               crangejoin      
      winsor2, gstats winsor  cwinsor        
      rangestat               crangestat        
      binscatter, binsreg     cbinscatter      
      psmatch2                cpsmatch      
      reghdfe                 creghdfe          
      ivreghdfe               civreghdfe    
      ppmlhdfe                cppmlhdfe    
      hdfe                    chdfe          
      cipolate                cinterpolate, cubic
    The README on GitHub offers some approximate speedups that I see on my machines. Your mileage will vary depending on your processor, memory, and the data you're working with. For instance, csort and cmerge are both unusual commands in that they require your entire dataset (the active frame, in post-Stata 16 terms) to be sent from Stata to the C plugin and then back again, rather than just a couple of variables. In contrast, when you run -creghdfe y x, absorb(f1 f2)-, only the variables y, x, f1, and f2 need to be transported. This data transport overhead turns out to be quite important. -csort- and -cmerge- will both perform best when your dataset is very 'long' and not very 'wide', and can perform arbitrarily poorly when you fix the number of obs and add more variables to your dataset. So it's hard to report even approximate speedups here, because it very much depends on your type of use case. For datasets with, say, tens of millions of obs and only 1-3 dozen variables, -csort- and -cmerge- are much faster on my machine. However, if you're working with some incredibly detailed survey data or something with, say, 1 million observations and 200 variables, -csort- and -cmerge- will likely be slower. (However, in this case you probably don't care about speed at all, because -sort- and -merge- will already run very quickly on such a dataset.)

    In the spirit of full disclosure, I am writing Statalist post today specifically because I just saw a new NBER working paper that was written to advertise a very similar, similarly vibecoded Stata command with a compiled plugin backend maintained by Johannes Schmieder (in this case just for -reghdfe- and -ppmlhdfe-). I am quite sure Johannes wasn't aware of my little project, which isn't his fault because I don't tend to promote my Stata projects online or in working papers, but I did want to get it out there in case this is of interest to the broader community and because it's been around for almost a year at this point and it feels ready to share. (And FWIW, since it is directly relevant to Johannes' NBER WP, on my machines -creghdfe- is about 1.5x to 2x faster than -fereg- on a variety of datasets). And although this is vibecoded, I've taken quite a bit of care to ensure it's extensible and the documentation mostly human readable everywhere. So, if you notice, you know, documentation that looks like a robot wrote it or whatever, just let me know (you can open a github issue or email me or whatever) and I'll get it fixed.

    If you write your own C plugins, this is all open source and MIT-licensed, so you can do pretty much whatever you like with it. A lot of effort was spent on finding the most efficient possible way to use the Stata plugin interface to move data between Stata's memory and the C plugin (most of that code is in src/ctools_transport.c and src/ctools_data_io.c). I'd encourage any program-writers not to reinvent the wheel and to take some of this code, at least as a jumping-off point.

    ctools owes a lot to the authors of the commands it replaces, especially Sergio Correia (-reghdfe-, -ivreghdfe-, -ppmlhdfe-, -ftools-), who also gave me tons of helpful comments and suggestions on this in the spring, and Mauricio Caceres Bravo (-gtools-, needs no introduction). Thanks also to the authors of -ivreg2-, -rangestat-, -rangejoin-, -cipolate-, -psmatch2-, -winsor2-, -binscatter-, and -binsreg-. A full list of kudos is on the GitHub's README, but do let me know if you think I've left anyone out who deserves some credit.

    Please report bugs or results that don't match on the GitHub Issues page: https://github.com/mdroste/stata-ctools/issues. While AI is quite good at writing thousands of test cases and the proper harnesses to make sure these commands behave as expected on a variety of datasets, it can't catch everything.


    Michael Droste
    Last edited by Michael Droste; Yesterday, 02:09.

  • #2
    Congratulations on this suite, which I imagine might help many users with enormous datasets for whom speed is crucial.

    Out of curiosity I looked at your forks of various commands for which I was an author or joint author.

    distinct is a command written by Gary Longton and myself. A tiny oversight: that's listed as a user-written command in some of your documentation, as just above, but the original code and authors (and various Stata Journal pieces around it) aren't mentioned in the program code or help for cdistinct.

    More important than this: It's been revised in various ways since first publication. Any users of cdistinct might want to know precisely which version dated when of distinct was that used in cdistinct. I regard that small principle as vital.

    Spot checks turn up similar small problems with other command files.

    Speaking for myself -- while at the same time imagining similar stances from other authors of code you've used -- I am very happy that you've found anything I have contributed to of use or interest. The code and help were all made public (and free) for people to exploit. But my idea on division of labour is this. I won't be checking anything you've written and if there are future revisions of any of my commands I won't check back on what you've done either.

    Comment


    • #3
      Hi Nick - thanks for this feedback. I completely agree with you. I'll do the following, and these will go up today (imminently, in the next few hours):
      1. Add a deeper attribution documentation that clearly indicates where each ctools command is "pinned" to a particular program version, linked off the main README.
      2. Make sure that the internal Stata help files for each command err on the side of being overly verbose about this.
      3. Be more clear in the main GitHub README and the internal ctools help file(s) on how versions were chosen. I do not want to add any work at all for the authors of original commands. If you've written a command that ctools has ported, and then updated it, you can also open an issue on GitHub or email me if you'd like it updated, that frankly requires way less work today than maintaining some of my old Stata commands from 5-10 years ago did. Or you can do nothing, and ctools will be much more clear that it is a ported snapshot of an existing command from a point in time that does not automatically track the underlying commands.

      These days, it is actually possible to monitor the commands that ctools ports for updates on, say, a weekly basis, update ctools accordingly, and even e-mail the update to Kit/SSC without any human intervention. It wouldn't even be that hard -- but that's a bit out of scope for now and is also kind of scary!

      And of course your point also applies much more broadly. For instance, users can't download historical versions of programs from SSC (with perhaps some minor exceptions like commands described in Stata Journal and whatnot). Stata doesn't really have the functionality out of the box to enforce versioning on user-written packages like every other language has these days (though Sergio Correia's -require- goes pretty far in addressing this!). I agree with you completely that being clear about versioning is important not just to ensure authors are getting their credit but to ensure that research in Stata remains reproducible. I'm pretty sure SSC predates modern best practices for package repositories (e.g. pypi), which typically store a ton of versions of packages and allow users/programs to choose or require specific versions. I do think I saw Kit mention that the future of SSC is being discussed with StataCorp; it would be great if the next-generation version of SSC was a bit more automated for submissions/maintenance, played well with -require- or a built-in equivalent in Stata that might appear in future versions, etc.
      Last edited by Michael Droste; Yesterday, 16:14.

      Comment


      • #4
        Michael Droste

        I am glad you agree with the principles of giving credit where credit is due and supplying good documentation generally. That is as it should be.

        Starting at the top, Stata itself has always been very careful about version control, as epitomized in the version command and the surrounding machinery. Ultimately, however, the only way to check what an early version of Stata did, exactly, is to find a copy of that version and fire it up, which can be very tricky. (I suspect that StataCorp, and perhaps no-one else) may have what in essence is a museum of all Stata code in different versions and antique computers on which to run them.) However, I have used every version of Stata since 2,05 and can't check more than a few of those. Changes in computers have made that too hard, but then again i almost never want to.

        Howwever, your focus and mine is on community-contributed commands. (For several years now, StataCorp have been encouraging us to use that term. The old term user-written isn't obsolete or wrong, and understandably it refuses to die.)

        I think your comments are a little unbalanced, putting most emphasis on SSC and not enough emphasis on the Stata Journal. I don't work as a StataCorp employee, but i have had a visible position as once an Associate Editor of the Stata Technical Bulletin (STB) and as one of the Editors of the Stata Journal.

        Right from the outset in 1994, the STB, and then the Stata Journal from 2001,has been totally supportive of authors not only publishing their code but also of supplying Software Updates. So, any authors not only publishing their commands but also maintaining them (anywhere between bug fixes and major revisions and extensions) has had the scope to maintain a complete series of versions of code, courtesy of StataCorp, as their fraction of an archive. In short, StataCorp is totally supportive of the idea of maintaining accessibility to all versions of such commands ever made public. I think it can fairly be said that back in 1994 they were ahead of the game.

        To describe the long and large history of commands published through the SJ as constituting "minor exceptions" is a fairly extraordinary choice of words. I hope that was just careless phrasing or that you were making a different point.

        Now SSC was set up independently of StataCorp and was always a choice available to user-programmers, and never a place where those user-programmers were obliged to post Stata code. In fact when StataCorp formalised the idea of a package, the guess of Stata developers was that most people would prefer maximum control of their packages by posting on their own websites. Some people did that, and continue to do so, but my guess is that there is far, far more use made of SSC. Now I have been a strong supporter of SSC from the outset and was a junior author of the first implementation of the ssc command, so nothing that follows is to be taken as negative about SSC. I am in strong competition to be considered its #1 fan.

        But, as you say, for some time the lack of support for maintaining multiple versions has been seen by many as a limitation of SSC. There are work-arounds that I and some authors too have used, principally renaming older versions of a command with distinct names. In some decades of doing that intermittently I can say that questions to me -- either directly or on Statalist -- about earlier versions of my commands have been very rare. So my own experience has been that in practice accessibility to earlier versions of command files is not a great practical problem. The principle remains admirable. Naturally, others may have their own experiences that may differ.

        (GitHub and any similar software do naturally offers other solutions here. I don't use GitHub, but there is no deep principle behind that choice. It is just immensely over-complicated for what I ever need, for the same reasons as make it invaluable to people working in different ways.)

        Comment


        • #5
          Hi Nick Cox, thanks again for your comments. I think we are largely in agreement. You made a perfectly reasonable suggestion about documentation and versioning, which I agreed with in its entirety, and I then made an observation about the limitations of SSC, which you also seem to agree with.

          You suggest that I might have been making a different point; I'm happy to make that more precise. A large number of community-contributed Stata packages are distributed exclusively through SSC, GitHub, or some combination of the two. For many of these packages, particularly those distributed exclusively through SSC, users have no straightforward means of obtaining historical versions. You can check yourself that among the 50 most downloaded packages on SSC at this point in time, a minority have ever appeared in the SJ or STB. My reference to minor exceptions was in this context. If the adjective "minor" was poorly chosen, I am happy to dispense with it. Nothing about the point I was making depends on the relative historical importance of the Stata Journal and SSC.

          I do find it a little peculiar to be taken to task for putting too much emphasis on SSC in a comment specifically about versioning in SSC. I had not intended a few passing remarks on SSC package management in a thread announcing a new software package to constitute a balanced account of the entire history and scope of Stata software distribution. I am quite happy to defer to others on that history (I turned three years old in 1994). My appreciation for the people who have built and maintained this infrastructure over the years should, I hope, be reasonably apparent from my original post and the GitHub repo.

          In any event, I would be considerably more interested in hearing what people think of ctools itself, which I think is the largest community-contributed command ever released (perfectly happy to be wrong about this too) by just about any measure.
          Last edited by Michael Droste; Yesterday, 18:17.

          Comment


          • #6
            Michael Droste

            You don't want or didn't expect a history lesson, but it seemed necessary -- and likely to be helpful for others -- given your statement in #2, which was no doubt written quickly, but is likely to mislead those less well informed than yourself.

            Stata doesn't really have the functionality out of the box to enforce versioning on user-written packages like every other language has these days ... I agree with you completely that being clear about versioning is important not just to ensure authors are getting their credit but to ensure that research in Stata remains reproducible.
            A merit of a threaded forum like this is that anyone can go back and check that I am quoting you fairly. But here you conflate the functionality provided by Stata for researchers with that of SSC.

            To restate, and to add a nuance or too

            1. Stata (meaning the company and what it provides) has been encouraging versioning of community-contributed commands through the STB and the SJ since 1994. Just as important as providing a place for code to be accessed has been a stress in programming Stata of stating the version of Stata you're writing for and the private provision of your own version number and its date, and as much history as you want to mention as comments in code or in your own help files.

            2. Using SSC was always a choice. Historic lack of support for versioning on SSC is acknowledged, but it doesn't seem to me to have bitten often.

            No doubt there always remains scope for temporary confusion. If group A and group B get different results and it turns out that A was using foobar 1.4.0 downloaded a while back while group B is using foobar 1.5.0 which is now the only version publicly accessible, that is more awkward than some would like, but progress can be made to resolving the difference so long as each group kept a record of their own reproducible code. Problems are more likely to arise because projects are less than reproducible than because Stata isn't allowing or providing scope for documenting what you did.

            On a different level, I don't see that every other language is enforcing versioning. For example, R is different, and there is if I understand correctly considerable rigour about what is distributed through downloads of core R itself and through CRAN, but beyond those it looks like the Wild West from afar in which packages can appear and disappear like leaves on the forest floor.

            Comment


            • #7
              A merit of a threaded forum like this is that anyone can go back and check that I am quoting you fairly.
              Nick Cox Indeed! I stand by what I said. Python, Julia, R, JavaScript, Matlab, Octave, SAS, Rust, Fortran, C - all of these languages support versioning from their primary package repositories and also allow for enforcing dependencies/requirements. Most of them also run or sponsor their package repositories, which says something about my "conflation" and who is ultimately responsible for the state of Stata package distribution as we near 2027.

              Once again, I'll stress that I don't think this particular thread is an appropriate place to have an extended discussion on package versioning and archiving, and I won't be taking this conversation any further.

              Thanks again for your thoughts.
              Last edited by Michael Droste; Today, 04:46.

              Comment


              • #8
                People don't own the threads they start and can't call close either. But I agree with you in this sense: I have said all I want to say for now.

                Comment


                • #9
                  It actually is possible (to some extent) to get previous versions of SSC packages; see https://www.statalist.org/forums/for...e-inaccessible

                  I would also be a bit cautious about the claim "that all these commands are about as fast as they could theoretically be". With multiple rounds of AI improvements, possibly using different AI models, it is likely that further gains can be achieved; see e.g.
                  Portela, M., and T. Tavares (2026). xhdfe: Fast High-Dimensional Fixed-Effects Estimation in Stata, SSRN discussion paper (August 2026), https://dx.doi.org/10.2139/ssrn.7271338

                  That is not meant to diminish your contribution.

                  I would expect StataCorp to improve their native commands in a similar way in future updates; this seems to be like an easy win. There might also be a trade-off between speed gains and numerical precision; StataCorp might not want to compromise on the latter.
                  https://www.kripfganz.de/stata/

                  Comment


                  • #10
                    Originally posted by Sebastian Kripfganz View Post
                    I would also be a bit cautious about the claim "that all these commands are about as fast as they could theoretically be".
                    I also second this caution. The only fair thing to say, in some general (and trivial) sense, is that the code that is written runs as fast as Stata interprets it. That statement is vacuous, if not accurate, but it does not mean that user-written code is optimized in any sense for computational speed or efficiency. It has always been my experience with any community-contributed packages for any programming language, that the code is written in such a way that works, and more skilled authors are more likely to produce solutions that are optimized in some sense, where less skilled authors may still provide "correct" results but not well optimized. The heuristic many authors seem to use is, "is it fast enough for what I want to do with it?" If the answer is yes, then it's good enough. You might get better performance by further refinement, but there will always be diminishing returns.

                    Comment

                    Working...
                    X