Some Bits: Nelson's log

25 posts in August 2015

Machine Learning: Support Vector Machines

After weeks of complaining my machine learning course had too much detail on the math and guts of ML algorithms and not enough on applying ML to real data, I got my wish. This week’s course on Support Vector Machines (SVMs) was pretty high level and breezy, and the homework even more so. And now I’m dissatisfied, feel like I didn’t get my week’s learning’s worth! Not that I’m complaining to have an easy week, but I wish there were a bit more brain-bending around application to replace all brain bending I was doing before figuring out the vector math and programming.

PS: I’ve created a Machine Learning category on the blog. And mucked with the theme. Boy, wordpress.com is super buggy and badly product managed.

Lectures

The main topic this week was Support Vector Machines, a supervised learning technique that was framed as being more powerful and practical in application than the previous techniques we used like linear regression, logistic regression, and neural networks.

Conceptually it works a lot like these other supervised learning systems. You define a cost function, but unlike the logistic cost function this one biases the system to prefer “large margins”. Ie basically it’s not enough to say “49% chance it’s category A”, the training is encouraged to say “10% chance it’s category A” instead. You control this bias/overfit tradeoff with the parameters C and sigma. C is much like our lambda from before, a damping factor to encourage small constants. (Confusingly, C = 1/lambda). sigma shapes the cost function curve itself, at least in the usual Gaussian kernel.

Oh yes, kernels. This is a neat trick where you can modify your input features with various functions. A linear kernel gives you linear regression (exactly? or more or less?). The Gaussian kernal is a good general purpose kernel. There’s a bunch of other kernals people use. And some magic allows this pluggable kernel function to be applied efficiently, so the training system runs quickly.

That’s where the lectures got a bit hazy. There was one whole 20 minute video dedicated to the math which was prefaced with “this is optional, and you should never try to implement this; use libsvm instead”. The main thing I learned from this is you can still understand speech when watching a video played back at 2.2x speed, even though the individual phonemes are no longer distinguishable. He skimmed over the math quite a bit, nothing was lost by ignoring it.

I never did quite understand why SVMs are better. We were advised they are best in applications with lots of training examples relative to the size of the feature set. Logistic regression is better if you have lots of features and few training examples. And neural networks may be better than SVMs too, but take longer to train. ¯\_(ツ)_/¯

Homework

The homework this week was super-easy, all about applying SVM to problems. Each of the 4 exercises was like 3 lines of code. The only hard part was learning Octave syntax for doing things like “find the element in the list”, which once again made me wish we were using Python.

Anyway we implemented two learning exercises. An artificial problem of “find the boundary between Xs and Os for 2d input points”. And a real problem of “build a spam classifier trained on this data set”. We were supplied with the SVM ML system itself, so all we had to do was write simple functions to compute the Gaussian kernel and boil a list of stemmed words down into a vector coding. It was kind of dumb.

The most useful assignment was writing a loop to try out a training system with various values of C and sigma, the tuning parameters for the SVM. And experimentally determine what values gave the most accurate trained model. I imagine this is the kind of thing you do in the real world frequently, and doing it well is an art.

The spam filter problem was also fun because it felt real. Took inputs from the SpamAssassin spam corpus. Used their code to crunch that text down to stemmed words, which we then coded into feature vectors. Push it through SVM and you end up with a system that classifies 98.6% of spam correctly! Which is not so great, I think 99.99% accuracy is minimal for a useful spam system. And even then you really want to measure that false positive rate carefully. But I had a whisper of an idea of how to apply this stuff to a real problem that is really solved with ML systems like what we are studying, and that was fun.

Application

Once again I find myself wanting to do this in Python. I really want a class which is “applied Machine Learning in Python”. I guess focussing on how to use Pandas and scikit-learn. Maybe someone has written that up already?

autossh for a persistent ssh tunnel

My Internet in Grass Valley is newly fast, but my ISP’s NAT setup  means I have no way of initiating connections from outside into my home network. Nice for security, awkward for hackiness. (They do offer a DMZ configuration but when I had them enable it on the previous link it never worked and broke traceroute, so I’m not asking this time.)

Instead I’ve set up a persistent ssh tunnel so that a port on my Internet server is always forwarded through to the ssh port on my Linux server in the house. That way I can ssh in remotely through the tunnel.

The only novel part of this is autossh, which is a wrapper for ssh that takes care of restarting the ssh tunnel if something goes wrong. autossh logs to syslog and has some configuration environment variables, none of which I needed to alter. It monitors for the tunnel dying and also periodically sends traffic through to make sure the tunnel is still working. ssh also has a keepalive mechanism it’s probably wise to use.

I mostly followed this guide for setting it up. Except for the Upstart config; after spending 30 minutes tearing my hair out I remembered I hate upstart and a good ol’ BSD 4.2 rc.local script would do just fine. Also I set stuff up to run as a separate user, and made an ssh config, so really it ended up being quite different. Steps:

  1. create a new “autossh” user on both machines with a shell of /bin/false
  2. set up ssh keys without passwords for this user, so that my house computer can log into my Internet server without any passwords
  3. Set up an ssh config for the tunnel for the autossh user at home.
    Host tunnel
      ServerAliveInterval 60
      HostName example.com
  4. Test that a basic manual ssh tunnel works as user autossh, without a password. This is important; first time you have to accept the ssh key manually!
    home$ autossh -N -R 2200:localhost:22 server
  5. Put the command to launch the tunnel in /etc/rc.local on the home computer
    su autossh -s /bin/bash -c 'autossh -fN -R 2200:localhost:22 tunnel'

Note the “-s” flag to su in the init script. Without that it runs as the /bin/false shell the user has which not only doesn’t work, but doesn’t give any useful error output.

Ubiquiti: less LoL lag

One nice change from with the new network, less lag playing League of Legends.

With my old hacky setup with triple nat and routers acting as a bridge, I had a lag pattern like thishacky lag

Now with the Ubiquiti gear I have a lag pattern like this:

Lag after

Note the lack of spikes! I have no idea what those were, something was getting buffered or something weird before.

I don’t think median latency or packet loss really changed, but I’m glad not to see those ping spikes. Although TBH they didn’t affect my gameplay much.

Ubiquiti success, sort of

Running a wire at my house isn’t working out, so I’m stuck needing a wireless link to get the 200′ outdoors to the base of a tree. Fortunately there’s power there! Today I replaced the hacky leftover router wireless link with a more permanent setup involving Ubiquiti hardware. So far so good, some things to improve.

The Ubiquiti equipment is interesting. In a lot of ways it’s just like a WiFi router with flexible firmware like DD-WRT on it. It has a wifi network interface and a wired network interface and various routing and bridging capabilities. But it’s more prosumer. Ubiqiuti has pretty solid firmware (airOS) and I’m impressed with details like the web-based discovery tool and the way it reconfigures itself quickly without rebooting. Also the wireless implementation seems much more solid than consumer gear. And the hardware is designed for outdoor use with directional antennas, and supports distances of 5 miles out of the box. Pretty impressive.

One massive caveat: the wireless link startup time is slow. Like 30+ seconds, maybe 5 minutes the first time. It appears to be scanning the spectrum for the right channel to use. Not sure why that takes so long, or why you can’t just rely on normal 802.11 frequency hopping for the 5GHz links.

I set up a Nano M5 and a Nano Loco M5 paired together as a transparent ethernet bridge. That configuration means those devices are invisible to the rest of my network. My router sits at the other end and gets DHCP from my ISP’s equipment. The wireless network SSID for the nanos isn’t even visible (and anyway it’s not standard 802.11). I think this is the right configuration for my purposes.

The configuration is like this:

  • A WISP POP a mile away with IP 173.195.173.1
  •    ... via a wireless link to ...
  • ISP hardware in my tree, acts as a DHCP server and NAT router.
    The WAN side is at 173.195.173.xxx
    The LAN side is at 10.33.1.1 and provides DHCP and NAT to my house
  •   ... via an ethernet cable to ...
  • Nano M5 in Access Point mode. WDS is enabled for bridging. This device has an IP address of 192.168.0.111 but that’s mostly invisible.
  •   ... via a 5GHz airMax link to ...
  • Nano Local M5 in Station mode. WDS is enabled for bridging. This device has an IP address if 192.168.0.110 but that’s mostly invisible
  •    ... via an ethernet cable to ...
  • My home router, an ASUS RT-N16 running as full AP + Router.
    The WAN side gets its IP address via DHCP from the ISP (via the Nanos). It happens to be 10.33.1.23 at the moment.
    The LAN side is 192.168.0.1 with subnet 255.255.255.0. Also provides DHCP and all the other home network services you’d expect
  •    ... via an ethernet cable or 2.4GHz 802.11 link to ...
  • Desktop computers, mobile devices, etc in 192.168.0.*

The good news is I’m not doing triple-NAT anymore. My router is doing all the real NAT work for my house. The ISP’s hardware is also NAT but I’ve taken pains to only have the one device connecting to it.

The main problem with this configuration is from my house network I can’t access the Nano status pages at 192.168.0.110/111. My router and the rest of my house’s devices think all of 192.168.0.* is on the LAN interface so won’t send packets out the WAN interface where they are. I could hack around this with static routes but that’s dumb. I should reconfigure the Nanos to a different subnet like 192.168.25.*. Then I add a single static route for that subnet in my router and I think I’m done. (I could set them to 10.33.1.* but that’s a bit funky, I definitely don’t want to risk those devices being visible to the wider Internet.)

The other small problem I have is the secondary PoE port on the Nano M5 isn’t working. In theory this should provide power to the ISP equipment in the tree. Power passthrough isn’t enabled by default but I fixed that, still not working. More tinkering required, for now I just use a second PoE injector.

This Ubiquiti firmware is pretty powerful and I feel like there’s some simpler configuration where I get rid of my house router entirely, use one of the two Nanos to be the router too. I’m not sure that really simplifies anything though, I’d probably still want the third box acting as an access point inside the house.

Update

I renumbered the Ubiquiti bridge devices to 192.168.1.110 / 192.168.1.111 and added a static route for them in my router. Works great. Next project; some sort of monitoring for them. They have SNMP and I find references to Munin plugins.

I also figured out the secondary PoE problem. I thought maybe it was total power; the Ubiquiti device wants 8W, the Cambium radio in the tree wants as much as 7W. So 15W total and the PoE injector only puts out 12W. But then I read more closely and discovered that the Cambium PoE implementation is reversed from the usual passive setup. Cambium puts positive voltage on pins 7 & 8, not 4 & 5 like everyone else. How stupid! Really dangerous, I’m lucky the magic smoke stayed inside the Cambium gear when I plugged it in. Maybe they engineered in some safety to overcome the perversity of using reverse polarity from what is common. (I hesitate to say standard, because there is no standard for passive PoE, although the 802.3af standard has a mode B that looks an awful lot like the passive PoE everyone but Cambium does.)

I’ve also discovered the radio in my house works in a closet, behind a relatively thick wall. Signal strength is degraded; airMAX quality is 78% compared to 95% with a clear view through the window, and max speed is about 200Mbps instead of 300Mbps. Still well above what I need for the 12Mbps Internet link though. Going to test it out, would be nice to not have to mount that thing outdoors or in the window.

Outdoor wiring

(Some very boring notes so someone else can wire this up)

Conceptually, we’re connecting a wire from the antenna in the tree to the Ubiquiti NSM5, one long straight wire. But it’s complicated because we need separate PoE injectors to provide power to both devices.

The black wire from the tree goes to the Phihong PoE module. It goes to the port on the left, labelled “Data + Power”. Very important to use the right module; the Cambium tree antenna uses non-standard PoE and this Phihong PoE module is special. The word “PHIHONG” is in the upper left of the label, beneath a spiral P logo. It’s the longer module, that does not say “Ubiquiti” in the upper right. The top one in this photo.

An ordinary short ethernet patch cable goes from the “Data” port on the right side of the Phihong PoE module to the “LAN” port on the right side of the Ubiquiti PoE module. This cable is currently a 3′ coil of white wire (would be nice to replace with a 1′ cable). This cable is not powered, not PoE, it just carries data between the devices.

Another ordinary ethernet cable goes from the “PoE” port on the left side of the Ubiquiti module to the Ubiquiti NSM5 antenna. It goes to the port on the right labelled “Main”. The port labelled “Secondary” is not used.

Finally, plug both PoE modules into AC power. There’s an LED on the back of the Ubiquiti radio to confirm it’s powered, but it’s pretty hard to see in bright sunlight. Once the devices have power they both take about ~60 seconds to establish wireless links.

WiFi protocol notes

I’ve been doing Wikipedia reading associated with my wireless experiments on how 802.11n works. Here’s some brutal summaries, note I’m totally ignorant of signals processing and believe taming the electromagnetic field is basically witchcraft. I’m sure I made a mistake somewhere.

802.11n notes

  • 802.11b and 802.11g are basically a single wireless signal on a single 20MHz wide channel. 802.11g uses orthogonal frequency division multiplexing to split that 20MHz up into 52 separate subcarriers. There’s 8 different modulation and coding rates possible in 802.11g, resulting in data rates of 6, 9, 12, 18, 24, 36, 48, or 54 Mbps.
  • 802.11n is based on 802.11g.
  • 802.11n’s main innovation is multiple antennas and MIMO.
  • 802.11n can optionally use a 40MHz channel. That’s a bit naughty at 2.4GHz; it means you overlap with pretty much every other 2.4GHz user around you. My iMac doesn’t appear to support 40MHz at 2.4GHz.
  • 802.11n can also run at 5GHz. (My router doesn’t.) I don’t think it runs any faster at that frequency, although the channel separation is nicer.
  • Max 802.11n datarate at 20Mhz channels is 288.8Mbps. At 40MHz it’s 600Mbps.
  • Multiple antennas also allow for MIMO, multiple-input and multiple-output. I don’t understand this at all but the Wikipedia page says this is about exploiting multipath effects to effectively get more useful signals out of the same bandwidth. This seems like complete magic to me.
  • A specific thing MIMO does is spatial division multiplexing. I think this is effectively a directional thing, ie: “I can talk to radios north of me and radios south of me independently”. Only I’m guessing this has more to do with orientation of the antenna, and may explain part of why simply rotating my antennas so they were not all parallel resulted in a better connection. (If the access point’s antennae are parallel then they are not spatially disjoint.) My iMac is currently enjoying two spatial channels to the router, which makes more sense if you think of rotational spatial division.
  • You get 1 spatial stream per antenna+radio (sort of), and 802.11n supports up to 4 antennas. My Asus RT-N16 is a 2x2 configuration so that’s effectively 2 transmit and 2 receive antennae. (There’s only 3 physical antennae, no idea how that works). That’s why it maxes at 300Mbps; only 2 spatial streams. With 20MHz bandwidth it maxes out at 144.4Mbps. My iMac gets 1 spatial stream sometimes and 2 most of the time.
  • 802.11n optionally supports a 400ns guard interval, half the space between separate data frames as the old 800ns. That seems to boost throughput about 10%. The Wi-Fi signal app on my iMac reports speeds that suggest I am using this, sometimes. (Ie right now: MCS index 7, but 73 Mbps).
  • 802.11n supports a bunch of different coding rates. The coding rate describes how much of the signal is reserved for redundant error correcting bits. My iMac is typically seeing a coding rate of 3/4 or 5/6.
  • 802.11n supports several different modulation schemes. That’s the digital to analog part of the radio, the way bits are turned into waves. My iMac is mostly using 16-QAM or 64-QAM, which corresponds to 4 or 6 bits per symbol. Neat visualization here
  • The coding rate, modulation, number of spatial streams, and maybe even the guard interval are varying frequently, at least once a second. Presumably the access point is picking which variant to use depending on the current error rate.
  • 802.11ac is the new hotness. It’s 5GHz, supports 80Mhz and 160MHz channels, 8 spatial streams, 256-QAM (with non-standard 1024), etc. If my arithmetic is right the spec could in theory go up to 8Gbps (compare 600Mbps for 802.11n). I think in reality you can actually get gigabit wireless speeds. But only if the spectrum is uncongested and the signal path is clear. My fancy ASUS RT-AC68U claims up to 1300Mbps at 5GHz. That seems to correspond to 2 streams at MCS index 7, which is 64-QAM 5/6 rate.

MCS Index

Most of the 802.11n options are summarized in a single number called the MCS Index. See also this table. MCS Index specifies the number of spatial streams, the modulation type, and the coding rate. Those together define how much data can be stuffed in a single subchannel. Combine that with your bandwidth (20Mhz or 40MHz) and your guard interval and you get a max data rate.

In practice my iMac mostly hangs out at MCS 7 or MCS 12. MCS 7 is a very dense modulation and coding, but only one spatial stream, and it’s reporting 73Mbps. MCS 12 is a less dense modulation but 2 spatial streams, and reports 78Mbps.

Misc other observations

The upstream bandwidth from my link is 12Mbps, so I don’t really care about any of these higher speeds. I’m much more interested in reliability.

I had my RT-N16 configured to use 40MHz but my Mac wasn’t using that. (From a quick search, Apple doesn’t support 40MHz at 2.4GHz.) So I knocked it down to 20MHz in the router and now I think I’m getting a stronger signal. -60dBm instead of -65dBm. I suppose that’s possible? I didn’t measure carefully.

I’ve got two wireless devices connected to the router; my iMac and an old WRT54GL running 802.11g. I tried making both of those wireless links busy, about 5Mbps each, and didn’t see any obvious contention. My iMac didn’t even drop down to 1 spatial stream which I was sort of naively expecting. That’s all as it should be: 802.11g promises 54Mbps bandwidth and I wasn’t getting near that. Nice that it really works.

Google’s new OnHub router does 802.11ac and 802.11n in a 3x3 configuration.

My 2013 iMac’s wifi antenna is behind the Apple logo in the case. Why? Because it’s the only part of the back that’s not made of aluminum.

Machine learning: picking the right system

Week 6 of my machine learning course.

Lectures: applying machine learning, system design

This week’s lecture was about using machine learning algorithms well. Great series of notes, the kind of thing I’m really in this course for. Focus in particular was on figuring out how to improve the results of your learning system and then evaluate the result. You have a lot of options to tweak the model and learning: more properties, more data, different learning rates. Which should you use? He gave a few heuristics better than guessing.

The first thing is splitting data into training and test sets. Keep the evaluation test data separate so you have something to test with that the learning algorithm never saw. Good advice. He also points out that you often use tests on trained systems to pick your trained system; you can’t use that test data (“cross-validation data”) for final evaluation either, since your metalearning system was picked to do well on exactly that data.

The other thing was defining “high bias” models (underfit models, too few parameters) and “high variance” models (overfit models, too many parameters). These are important concepts! Then he gives a test to figure out if your learning system is one or the other, which is basically looking at error rates. Systems that train to low error but then test badly are high variance, overfit. Systems that train to high error and test badly are high bias, underfit. I get the intuition for this and look forward to apply it in the homework.

Finally we moved on to ways to build systems and evaluate them for success. Really nice exhortation to build a quick and dirty system first with the simplest features and data you can get your hands on. Start working with the problem and you’ll understand it better, then you can make an informed decision about what extra data you need. Also an interesting observation about the usefulness of very large datasets. Having an enormous amount of test data means you can use more complex models with less bias, and be confident that you won’t overfit your training data just for the sheer size of that training data set.

Ng defined precision and recall for measuring an algorithm’s correctness, also boiling those two numbers down into a single F-score for ease of comparison. Useful in particular for skewed datasets where you may be classifying something that’s only True 1 iin 1000 times.

Homework

This week’s homework has us loop back and implement the very first model we learned, linear regression, then test and evaluate it according to some of what we learned. I didn’t care much for the linear regression part, but the the hands-on application of learning systems and error measurements was great.

The first half of the homework was “implement linear regression learning with all the bells and whistles”. We’d not done that before, only logistic regression, so it was similar and yet different. Not too challenging really, a bit repetitive from previous work, but reinforcement is good.

The second half of the homework was “train a bunch of learning models and measure their error”. Specifically comparing the error on the training set vs. the training on our reserved cross-validation set, and graphing learning curves, etc. This is a sort of meta-machine learning, choosing the parameters for our machine learning system so that we get a well trained model.

We looked first a a truly linear model, trying to fit a straight line to data that’s roughly quadratic. Lots of errors. The learning curve shows us that adding more data points isn’t really going to help make this model more accurate, it is over-biased. So then we switched to an eighth order polynomial model but trained it without regularization. That fits the training data great but fails cross-validation, because it is high variance.

So finally we applied regularization in the learning model, the mechanism that encourages the learning to low-magnitude constants for the polynomials. The encouragement strength is governed by the value lambda. So train lots of models with low lambda and high lambda and see which lambda is best. Lambda = 3, that’s best! At least for this problem.

Conclusion

I’m really itching to apply this stuff to my own problems now, to make it real. But I’ve got to solve two problems at once to do that. I need confidence in my own code without the safety net of homework problems with calculated correct answers. And I really want to redo this work in Python, to get out of the weird Octave world. Taking both leaps at once is foolish. I should either bring a problem of my own into Octave once to apply my proven code to new data. Or else port the homework to Python first and verify I still get the right answers to prove my new code. I tried the latter already and got frustrated, should try the former.

Project idea: open stuff with VLC

VLC doesn’t install itself as the default handler for media files like .m3u or .mkv or whatever. Not sure why, but the documented process is tedious.

I should write a simple script / program to set VLC to be the default app for a bunch of types that VLC supports. Maybe absolutely everything that would otherwise open in iTunes is a good start :-P The program duti is a good start on how to set associations in MacOS. It seems to work by using the Launch Services API.

Wireless ethernet bridge success

Frankenstein network success! I managed to turn an old Linksys WRT54GL into a wireless ethernet bridge. It was remarkably difficult. Despite a long history the WRT54GL seems end of life to me, a lot of the hacker firmwares don’t really support it well anymore.

The goal here is to bridge my new fast Internet access from the tree 200 feet away to my house. The router up there works great but right now I don’t have a wire into my house, so only wireless devices with good antennae can use it. A wireless ethernet bridge is perfect for that; it turns that old WRT54GL into what looks like an ethernet switch connected to the router via a magic wireless wire. In theory. Note the WRT54GL is doing very little else in this configuration: no routing, no DHCP, no DNS, etc. It’s acting more like a layer 2 ethernet/wifi device than a layer 3+ Internet device.

The big problem I had was trying to make this work with Tomato/Shibby firmware. It supports ethernet bridging but has some weird and spooky restrictions around WPA2 and bridging mode. I never could get it to connect on the wireless link, probably because of that authentication mismatch.

So back to good ol’ DD-WRT, a 2009 build named dd-wrt.v24_mini_wrt54g.bin. Downloaded that, followed some instructions, and bridging was working in just a few minutes.

I’m grateful I understand arp; there’s no way to debug or reason about what a bridge is doing without it. The Tomato firmware doesn’t even really present the arp data to you very clearly, you have to ssh in and run the arp binary to see it.

So now I have 4 ethernet ports with fast internet inside my house. Albeit as a temporary setup. How do I get the rest of the network using it? I can just plug the switch for the wired devices into the bridge and it should all work, now DHCPed and routed by the temporary router up by the tree. The problem is I have a couple of wifi-only devices in the house with antennae too weak to reach the tree. So I could repurpose a third router and turn it into an access point for the tree network, that’d be the “right” way to do it permanently. But I want to be able to undo this all and so not screw up that third router, the one that’s my current normal (slow Internet) router.

So instead I’m considering plugging that house router’s WAN cable into the bridge. That should work with much less disruption to the rest of the house network and easy to undo. But it implies we’re doing double NAT for everything which is pretty gross.

Update: I went with the double NAT setup; basically changed my primary home router’s WAN connection from the old Internet link to get Internet via the bridge, which goes to another NAT router, and then the antenna. It may actually be triple NAT; I think the antenna hardware does NAT too. It’s gross but none of my client computers seem to care much. UPnP/NAT-PMP doesn’t seem to be working so no inbound connections, but I can live with that for now. I realized later the “right” setup is for the wireless ethernet bridge to be outside near the tree / antenna, then have my internal router get its WAN connection via that WiFi link. I think DD-WRT or Tomato can be bent to do that but the firmware all assumes your WAN link is coming in that ethernet port on the back. Too much hacking for a temporary thing.

One other thing to mention / option for making this work is WDS, a sort of bridge-like system for wifi networks. The key thing is it allows a device like my WRT54GL to both use the wifi interface as a client and also serve as a repeater / second access point serving that exact same wifi interface. Both Tomato and DD-WRT claim to support it, but it seems pretty spooky to me. Also lots of warnings online it’s not a well defined standard and compatibility is a problem.

I’ve spent a lot of time on a hack that’s only going to be used for a few days. The outside router is sitting in open air on top of a post! Good thing it doesn’t rain in California anymore.

Video bitrates

Interesting post from Riot explaining why they don’t broadcast 1080@60fps. Long story short, they say it’s too much bandwidth. I was curious how much bandwidth it really is so I used youtube-dl to look at the streams for the DotA 2 final this year.

For MP4 streams the bitrates for video only are:

Resolution   FPS     KBPS
       144    15      120
       240    30      255
       360    30      610
       480    30     1148

       720    30     2243
       720    60     3362

      1080    30     4191
      1080    60     5592

Bottom line: 1080@60 is 2.5x the size of 720@30. And 720@60 is less bandwidth than 1080@30. IMHO the faster framerate offers more of an upgrade than the extra scanlines.

Edit: the LCS live broadcast on Aug 22 is 720@60. 3800kbps total at the router. Format 298, which is h264.

For completeness: YouTube also offers VP9 streams. They’re mostly smaller except 1080@60, but the scaling is about the same. Here’s all the streams on offer.

160          mp4        256x144    DASH video  120k , avc1.4d400c, 15fps, video only, 34.59MiB
278          webm       256x144    DASH video  131k , webm container, VP9, 15fps, video only, 35.95MiB
133          mp4        426x240    DASH video  255k , avc1.4d4015, 30fps, video only, 77.52MiB
242          webm       426x240    DASH video  281k , vp9, 30fps, video only, 75.53MiB
243          webm       640x360    DASH video  525k , vp9, 30fps, video only, 141.57MiB
134          mp4        640x360    DASH video  610k , avc1.4d401e, 30fps, video only, 147.37MiB
244          webm       854x480    DASH video  957k , vp9, 30fps, video only, 254.94MiB
135          mp4        854x480    DASH video 1148k , avc1.4d401f, 30fps, video only, 293.53MiB
247          webm       1280x720   DASH video 1945k , vp9, 30fps, video only, 510.17MiB
136          mp4        1280x720   DASH video 2243k , avc1.4d401f, 30fps, video only, 561.60MiB
298          mp4        1280x720   DASH video 3362k , h264, 60fps, video only, 917.39MiB
302          webm       1280x720   DASH video 3372k , VP9, 60fps, video only, 815.76MiB
248          webm       1920x1080  DASH video 3580k , vp9, 30fps, video only, 896.15MiB
137          mp4        1920x1080  DASH video 4191k , avc1.640028, 30fps, video only, 1018.78MiB
299          mp4        1920x1080  DASH video 5592k , h264, 60fps, video only, 1.55GiB
303          webm       1920x1080  DASH video 5833k , VP9, 60fps, video only, 1.38GiB

CSV query tools

I do a lot of work with CSV files, and up to now I’ve been mostly doing clumsy stuff with standard text tools like “awk -F,” and the like. Here’s a roundup of some Unix command line tools for working with CSV files, lifted from One Thing Well

  • xsv: slice, split, summary stats, etc. also supports creating a quick index to accelerate things. Seems pretty solid. Rust program, which is awfully weird, but he provides a Linux binary.
  • csvkit: suite of programs for manipulating CSV. Includes import/export to JSON, Postgres, Excel, etc. Also has a SQL query via in-memory sqlite3. Python program.
  • Miller: “like sed, awk, cut, join, and sort for name-indexed data such as CSV”. More limited queries than xsv or csvkit. But it embraces more input file types, including CSV files that change schema and arbitrary keyword/value data. Seems perfect for the “long list of JSON object” files I often work with. (Although no JSON support?!)
  • csvfix: thin docs, another xsv-style tool. Has more operations than other tools.
  • q: SQL queries on CSV files via sqlite. Python program.
  • TextQL: SQL queries via sqlite. Go program.
  • fsql: SQL queries via some Perl SQL implementation. Supports JSON and YAML.

I just tried xsv and it’s quite nice, may be the closest to what I need day to day. I’ve used q before and remember it working nicely, albeit a bit slowly. Arbitrary SQL is appealing.

WiFi transmit power readings

I’ve got a router outside about 200 feet from my iMac with a clear line of sight through a window. I’m running 802.11 at 2.4GHz over the distance. It works surprisingly well. I’m in a quiet rural area. The signal strength isn’t great and the speed isn’t what I’d like. The Tomato firmware I use lets me override the transmit power in the router, numbers from 0-250. Default is 17 or 42, folk wisdom is that up to 70 is “safe” although other folks say any setting is safe. Those settings may be throttled too, depending on what country you’ve configured the router to be in. Also apparently too high and you start getting distortion. Or not. Wireless is spooky.

Here’s some readings on signal courtesy of the WiFi Signal Mac program. Routers are running Tomato and/or Shibby and are using stock antennae. Readings taken under light to no load. All readings are approximate / variable and sloppy enough to not be very good. It’s not clear what these settings really mean; people call them “milliwatts” but it’s not clear that’s true.

All this stuff is using channel 11. 20MHz wide, AFAICT, even though I configured for 40. Measured noise is -79 to -82 dBM. I wish I understood how noise worked better. I’ve been able to use this link even when reported noise was higher than signal. Is that a thing WiFi can do?!

iMac 2011 tests:

Linksys WRT54GL 802.11g, 200 feet away

  • 12: -72 dBm
  • 42 (default): -75 dBm
  • 70: -72 dBm
  • 200: -67 dBm

ASUS RT-N16 802.11n, 200 feet away

  • 80: -68dBm
  • 200?: -68dBm. (May be limited by US country setting.)

a different ASUS RT-N16 802.11n, 10 feet away

  • 17 (default): -50 dBm

Macbook Air 2011 tests

ASUS RT-N16 802.11n, 2 feet away

  • 80: -32 dBm

ASUS RT-N16 802.11n, 200 feet away.

  • 80: -69 dBm

No real conclusions from all this. Boosting power might or might not make a significant difference; measurably it does with the WRT54GL, not so much with the RT-N16. The RT-N16’s signal strength also seems a little better, which is sort of expected since it’s 5+ years newer hardware with fancier antennas, etc.

One thing I didn’t record systematically is the improvement 802.11n brings. With the 802.11g links my actual link speed seemed to be 2Mbit/s as measured by Ookla Speed Test. I can get the full 12Mbit/s with the 802.11n. The reported theoretical Mbps of the wireless link is also significantly faster, as expected. The way I understand this is that 802.11n makes better use of available signal than 802.11g.

See also this discussion which shows improvements from -73 RSSI to -60 RSSI as power went from 1 to 55. Another graph shows improvements from -80 to -72 RSSI as power goes from 0 to 80. This article is interesting as well.

Update: antenna arrangement

Woah! I rearranged my antennas and picked up 5-6 dBm, which when I only had 6 dBm over noise basically doubles the SNR.

All the tests above are with the 2 or 3 antennas on the router all pointing straight up. Turns out that’s dumb, you want them perpendicular. I arranged the 3 antennas on the RT-N16 into a W shape (45 degree angles) instead of all 3 straight up. Went approximately form -68dBm to -63dBm. Who knew?

Update 2: hot rod antennas

I tried some third party antennas, advertised as 9dBm gain (compared to 3dBm stock). Not impressed. Measured signal strength at my iMac was the same, about -63dBM with both sets of antennae. The new antennae are over 2x as long, which I guess is probably good? But the connector isn’t stiff enough and it doesn’t hold its own weight at the 45° angle I figured out was better. I think I won’t be using these.

Update 3: symmetric readings

I forgot that my RT-N16 wifi router 200 feet away has a report of RSSI too, so I can see the signal from the other side. These readings are all +/- 3dBm fluctuations.

  • iMac hears -65. N16 hears -58
  • WRT54GL hears -61. N16 hears -52
  • MacBook Air hears -73. N16 hears -71

These devices all report noise measurements too but its’ radically different, like -75 dBm on the iMac and -92dbM on the WRT54GL. No idea what that means.

Update 4: San Francisco tinkering

I tried to apply what I learned about improving wifi strength in San Francisco. Different environment: I’ve got 10+ networks in view of me (mostly 2.4GHz?) and the walls of the house generate a lot more interference, I think because of metal lath in the plaster. Anyway, what I learned:

  • Changing xmit power from 42mW to 100mW didn’t help at all
  • Repositioning the antennas to a spread out W made things a little worse, if it had any change at all.
  • 2.4GHz and 5GHz work equally well downstairs, about 32dB SNR. Upstairs (away from router), 2.4GHz has a significantly stronger signal. like 10-20dB SNR vs 5-10dB.
  • Fancy ASUS routers have an “interference mitigation” setting that seems designed for dense urban areas. Turning it on didn’t help signal strength at all, may even have harmed SNR by 2dB or so. Nevertheless I’ve left it on with some theory it will help.

I wish there were some easy way to measure reliability. I don’t care about max throughtput nearly as much as I do reliable packet delivery at whatever speed.

LoL dotmap

Fresh off my heatmap attempt I made a second map of a single LoL game using a dot map. One dot per player recorded position (28,000 in all), colored by team.

Screen Shot 2015-08-17 at 6.04.56 PM

I think this treatment works better; the team color is really important information. But I miss the emphasis of dwell times that the heatmap accumulation algorithm gives. I’ve tried to fake it by using dots with 20% opacity but that’s pretty bogus. (Also easy to fudge, depending on dot size, opacity, and stroke weight you use.)

Still, an improvement, and I’ve also got a data extractor that’s creating more structured data so I can track individual players.

I did this in D3js because it was easy to. But I want to produce a static final output so there’s really no need for Javascript. I should look into data plotting tools in other languages. Maybe this is a time to try out some more of the big data Python tools, or see what Octave has up its sleeve. I think something like the heatmap algorithm is really what I want.

First light: League of Legends heatmaps

I took a crack at rendering the position data I found in the League of Legends live matc stream. Here’s a first take on TSM v TL game 1

Screen Shot 2015-08-17 at 3.59.13 PM

Interpretation

Not bad, it at least looks recognizable. The main trend is that there’s more activity on blue side (lower left) than red size (upper right). That matches what happened in game; TSM was red and they won, and dominated. The other basic pattern is you see the basic shape of the map and the paths through the jungle. This is expected.

But then it gets more subtle. I love the two blobs at upper left. I think these are times when TSM’s jungler was hiding in those bushes ready to gank for TSM’s top laner, will have to watch the game again to verify he really did spend a lot of time there. Als interesting to see the relative bias of activity over towards Baron instead of Dragon, I suspect that’s not a universal for all games.

Improvement

Lots to do to make this better. Some inspiration: this NYT treatment of similar data, which takes data from many games and uses dots instead of a heatmap. However my goal is more to highlight what’s interesting about a particular game, so have to apply their many-games approach carefully. And also these DotA maps which are basic but complete works.

#1 problem with my treatment is the single color scale: I really want red vs blue ramps for the two teams. But then I don’t want to mix them to purple! I suspect the heatmap treatment is really not the right tool here, I should consider dots like the NYT map. It’s about 26,000 dots in total per game. (600 per minute, games seldom go 60 minutes.) Also should look at hexbinning or whatever the cartohipsters are doing these days.

I’d also like to examine the time axis, see how the movement spreads over time. I don’t really want to make some interactive visualization though, a static image is better. I like what the NYT did breaking the game up into three phases.

Finally it’d be nice to be able to pick out individual players. Particularly the support and jungle since they roam more, but also bot and top to see what happened with lane swaps.

Implementation

The heatmap rendering is from heatmap.js. I like it for being a straightforward canvas implementation, and it is fast as promised. But the rendering is very limited, in particular I can’t come up with any way to render two categories of data in different colors in the same heatmap. (And the canvas is opaque, so I can’t just draw two superimposed, which would be awful for other reasons too.)

The data extraction is some dumb-ass Python to pull the position fields out of the stream data. Quick and dirty, need to clean it up if I do this for real. If a character doesn’t move I don’t draw their position twice right now. Also the stream data is remarkably messy, I need to do extra work to detect game start and end and filter out data from the previous game that sometimes got mixed in. And I should preserve per-player data to allow more flexible visualizations.

Machine learning: backpropagation shitshow

Frustrating week in the machine learning course. We learned how to implement backpropagation in neural networks. Or at least we pretended to.

Lectures

Ng’s lectures skate over the math pretty fast and there’s like 3 separate snippets reassuring “if you don’t understand this don’t worry, it’s hard and I don’t always remember either lol!”. I think this course tried to walk the line between either really doing the math or not and fell in a gap in the middle. I’d prefer to have skipped the math entirely. I kind of did, honestly, and fell back on my “how do I fake this” survival skills from the few college math classes I didn’t like.

The useful part is Ng also emphasizes the intuitions and mechanical logic of what backpropagation is doing, and that I think I understand. Forward propagation is creating a mesh of hidden layers that map inputs to outputs with hidden weights. Backprop starts at the output layer and observes the error, how far the network’s output is off from expected output. It then tries to apportion that error to the previous layer’s nodes by spreading the error backwards, weighted by the activation parameters. And so error is propagated backwards through each layer and in the end you have some idea how much each activation weight contributed to the mistakes the output made.

More concretely, backpropagation gives you a cost function J and its partial derivatives where each activation weight in the neural network gets a fair share of blame for the error. With cost function in hand you can run a function optimizer to find the activation weights that minimize the cost. (One fact Ng skated over; this cost function is no longer convex, which means the optimizer might get stuck in local minima. He mentions the problem and says not to worry about it in practice. Um, ok).

One fun thing in optimizing neural networks: if you start one out with node having constant activation weights (say, all zero) then all the nodes look the same and error is apportioned equally, so nodes don’t train separately. To break this degenerate symmetry you start training the network with randomized weights. Reminds me of the Big Bang and the lumpy cosmic microwave background.

Homework

The homework programming exercises are the only way I feel like I’m really learning anything. They’re reasonably good.

However, this week’s lecture + assignment clearly specify “don’t try to vectorize over the 5000 training inputs, just use a loop”. But then the tutorial that’s my real lifeline to implementing these assignments is a vectorized implementation! Which is it, teacher? I’ve mostly preferred implementing the vectorized versions, both because it’s faster to run and because it’s a closer match to the math equations from the lectures. It’s sure nice avoiding writing lots of for loops. But the teaching materials really need to decide to either vectorize everything or not, this stuff in conflict is a mess that I imagine loses a lot of students.

While I’ve been doing vectorized implementations, really I’d prefer to not vectorize over the training inputs. Write all my code to process one training example at a time. That’s the way a lot of stuff works in the real world anyway.

Anyway I stumbled through the notes and managed to implement backpropagation. I think I understand how it works too, although I just accept the provided cost function and derivatives as gospel truth rather than having done the derivation myself. And in the end I’ve trained my own neural network to recognize handwritten digits. Yay!

One fun thing in the homework is they visualize the hidden activation layer. That layer has 25 nodes. This image shows for each of those nodes, how much it weights the value of any particular pixel. If you squint you can convince yourself this hidden layer is doing some feature detection, like the bright vertical line in row 2, column 3. Also clearly the corners of the image are not useful to anything.

Screen Shot 2015-08-16 at 5.59.57 PM

I thought the technique of gradient checking was interesting. Backpropagation (and other cost functions) require you analytically divine the partial derivatives of your cost function, or in my case copy them blindly from the lecture notes, and then implement this in code. It’s pretty easy to have a bug. And apparently subtle errors in the gradient function result in neural networks that sort of converge but just not very well, so you might not notice the bug. Ng suggests as a backup check that you also numerically approximate the derivatives, by evaluating the cost function an epsilon away from some value and thereby calculate the gradient. Then check this numeric approximation is close to your analytically derived implementation. I like the idea, it’s a sort of interactive debugging technique. Also begs the question why bother with the analytic derivative at all, why not just use a numerical approximation? Because it’s expensive to calculate the numeric approximation, that’s why. And also it’s less accurate.

I also appreciate the role regularization plays. Apparently it’s not hard to overfit a neural network to input data. Ie: it is 100% accurate on your input data but then its overfit and may not work well on real data. The lambda regularization parameter is a damping applied to the gradients to encourage all the parameters to be small numbers, which apparently is the way you keep a neural network honest.

Here’s a picture of the hidden layer’s activations for an overfit model. Notice how there’s no obvious feature detection? At least, there’s no obvious vertical stroke detector like there was in the previous model. The accuracy of this model is 100%, but it may be less useful when applied to data it wasn’t trained on.

Screen Shot 2015-08-16 at 6.01.36 PM

That’s the kind of machine learning trap I’m taking this course to learn more about. I sort of understand the math behind why lambda works, but I can see it would take a lot of experience applying this stuff to real problems to really get a feel for how to set it right.

In the end I really hope to never, ever implement a neural network again in my life. I do honestly just want to use someone else’s neural network library. I do feel some sense of accomplishment having built my own though. And my real goal here is to understand a little of what’s going on inside the black box so I can use it better. I gather neural networks have a lot of subtle traps.

I still have to go and apply this stuff to real data I really care about. I started trying to do that a couple of weeks ago, in Python, but got frustrated trying to learn Pandas and scikit-learn and iPython notebooks all at once.

LoL live match stats

New feature on Riot’s pro game broadcast site: a live stats board. It updates once a second in your browser showing you game stats. Also features for Twitter messages, game stream info, etc. It’s the stats I’m interested in.

Stats scoreboard

Here’s the data on display:

  • Match type. Game #. Games won / lost by each team. Team and player names.
  • Kills in current game. Also objectives: inhibs, barons, dragons, towers.
  • Total team gold.
  • For each player: kills/death/assists, CS, and gold.

Data contents

The game stats are implemented with a web socket. (There’s also some JSONP being polled for other features; the stats are a web socket.) I wrote a Python program to record the data. They generally send one message a second, about 500 bytes, updates to things like player gold, kills, etc. It’s a pretty efficient implementation.

The data on the web socket is mostly what you’d expect to implement that display. Messages usually contain updates on player stats: total gold, current gold, experience points, and player position. Variables are only in the JSON blob if their value has changed. A bunch of oddball updates sometimes come through for things like CS, player kills, etc. And then teamStats updates for tower kills, etc. They’re also tracking player double kills, triple kills, etc. Nothing in the stream about item purchases that I’ve seen.

There’s also some special messages. The first message on the socket is about 14k and contains all the data that ordinary isn’t changing, stuff like player name. When a new game starts the info about what champions are in the game is sent along. When a game ends there’s a gameComplete message. That kind of thing.

The most interesting thing I’ve found in the data stream is player position. It’s currently not being used by Riot’s web client. Should be possible to use that to animate a version of the game. riftwalk.gg had something like that based on replays before it got shut off, would be nice to feed this stream to that visualization code.

Technical details

My Python client is having the socket closed on it every 90 seconds. I just re-open it for now, seems to work. The web client in Chrome doesn’t seem to be doing that. Wireshark tells me that there’s a ping/pong Chrome is exchanging every 45 seconds. I’m guessing the Python client isn’t responding to pong and after two failed pings the connection closes. A bit confused why the pong doesn’t come through, the Python library looks like it just handles that for me.

Update: I looked in Wireshark and found the Python client is sending pong responses, but they’re getting TCP fragmented into two packets maybe because of the way the async writing code works. I’ve opened an issue on GitHub seeing if my analysis is correct and whether it’s something that could change. Update 2: I guessed right! The author changed the code to not fragment the packet and now I can stay connected. Yay!

The web socket hosted at ws://livestats.proxy.lolesports.com/stats. The socket requires a JSON web token to connect, which is some signed blob, although it’s not tied to any personal secret like a password login. I pulled one out of my browser and decoded it via jwt.io, it contains a bunch of IDs. Also has what looks like an expiration date, token is good for a week. I just pulled the token out of my browser and reused it in the Python code.

Mac screen capture: creating League of Legends highlights

I felt like a huge nerd today and wanted to record a video highlight from a League of Legends. Lots of steps here to capture the game itself, capture video and audio on the Mac to a file, convert it to something usable, then upload it. Here’s all the steps.

Generate content: record game replay

The service replay.gg will record all your League of Legends games for you. It’s terrific! Using it you can watch one of your games later in the observer client. I use this to get the exact game scene I want to capture.

Capture content: video and audio capture

The Mac does not make it easy to capture full screen video and audio. I used to use the commercial product Screenflick to do this but it’s pretty buggy. So this time I did the capture with Open Broadcaster Software, which is a free. The UI is a bit more hackerware but for my purposes it’s perfect.

OBS records video pretty much right out of the box. I tinkered with the Advanced Output settings to record at the bitrate of 10,000 (overkill) using the faster preset. Note that OBS is doing h.264 encoding live while you go, so it’s taking CPU power. The “slow” preset definitely interfered with my game framerate. (Screenflick records with a very fast, disk intensive codec and then re-encodes later, which is kind of nice.)

Audio is a problem. Update: see this second post about sound. OBS recommends WavTap but I couldn’t make it work. Instead I installed SoundFlower, which also works well with OBS. Basically SoundFlower installs a kernel module that’s a new loopback audio device. You use the Sound control panel to tell the Mac to make SoundFlower 2ch the default audio device. SoundFlower then passes that through to your actual headphones or whatever, while also making the sound stream available to apps. Note that starting with Yosemite it’s getting very hard to run custom kernel drivers in MacOS. Thanks a lot, Apple.

Now I have OBS recording movie files to my hard drive of whatever is on my screen. Yay!

Edit content

The next challenge is editing the capture down to what you want to share. I’m allergic to iMovie, and AFAIK there is still no good free simple “let me cut 15 seconds out of my video” GUI tool for Macs. I ended up using ffmpeg to do this with these instructions. ffmpeg lets you pick to the nearest millisecond, but irritatingly VLC won’t show you milliseconds in playback, so precise cuts suck.

Here’s the command I used to cut from 00:02 to 00:19 of my recording and re-encode it at decent quality. Unfortunately you can’t just use “-copy” in ffmpeg because that doesn’t properly trim the audio for some reason; you have to reencode.

ffmpeg -i obs.flv -c:v libx264 -preset slow -crf 20 -ss 00:00:02 -to 00:00:19 out.mp4

Man I’d like a simple GUI program that lets me watch the movie and set a start time, an end time, and press a button to do this cut for me.

Share content

Now you have an ordinary MP4 movie file you can share anywhere. I uploaded it to Streamable, a lightweight hosting / sharing service for video that plays nicely with Reddit and friends. They re-encoded it to a 2260 kbps vp8+vorbis file which still looks pretty good. In particular I think they kept my 60 frame per second source, much appreciated.

LoL protocol: channels

I sliced my ~20 minute ARAM game packet capture a different way, looking at channel numbers. Enet is a multichannel protocol, it can contain up to 0xff different channels. No idea what guidance there is for using this feature, but here’s what I found. Note that my parser still breaks on some packets, so I discarded things that look malformed or very rare. Ie: report is not 100% complete.

Channel 0xff: control. 2%
Starts the game off with a CONN/VCON pair.
For the whole game, client sends PING roughly twice a second. It gets an ACK about 35-40ms later (my client’s RTT.) A new ping is sent almost exactly 500ms after the last ACK is received.
For the first three minutes, server sends PING roughly twice a second which then client immediately ACKs. Server pings mostly stop after 180 seconds, although I did see a single server PING at 519, 848, 964, 1666, and 1928 seconds.
The PING packets are generally just 12 bytes big, but occasionally are bigger: 30 or 31 bytes is next most common.

Channel 0x03: server to client. 42%
Entirely reliable packets. A whole lot. 54% are small (14 bytes is most common), but some get to 100s of bytes. I imagine this is the important game state.

Channel 0x01: client to server. 35%
This contains all of the traffic the client sends the server. A healthy mix of Enet packet types (reliable, unreliable, and unsequenced). 72% of these packets are very small (14, 24, or 25 bytes). Some are a little bigger.
I ran a second game which was a custom solo game for just 4 minutes with me doing nearly nothing, almost no input. There were almost no reliable packets sent by my client at all; that is consistent with the reliable packets being used for user input. I wonder if all the unsequenced/unreliable traffic is used for bot detection, tracking the user’s mouse position or other signals from the client?

Channel 0x04: server to client. 19%
A bunch of SUNR packets first; those are unreliable but sequenced. Then a stream of SUNS packets; those are unsequenced. No one packet length dominates, the most common is a 40 byte packet at 9%. But almost all the traffic is in the 40-60 byte length.

Channel 0x02: server to client. 1%
Entirely unreliable packets. Not many. 71% are 25 bytes.

Channel 0x05: server to client. 0.03%
This is a mystery. It’s very low traffic, 25 or so over the whole trace. But they’re there and they are sequenced.

Conclusions

I think channel 3 is most interesting as a source of lag; that’s the server sending reliable packets to the client. Channel 1 is also interesting since it contains the clients’ reliable packets to the server.

I just noticed that SUNS packets (unsequenced) still contain sequence numbers. That’s handy for monitoring out of order and loss even if the protocol doesn’t treat those as errors.

I also did a quick spot check of this data vs. a custom solo game I recorded for ~4 minutes where I did almost nothing. The traffic distribution was roughly similar other than the difference in  channel 1 I noted above.

Here’s a table of popularity of packet types and channel number.

    1469 .4164 PING   :ff
    1459 .4135   ACKK :ff
     299 .0848 ACKK   :ff
     298 .0845   PING :ff
       1 .0003 CONN   :ff
       1 .0003   VCON :ff

   38364 .2362 SUNS   :01
    8541 .0526 SREL   :01
    8540 .0526   ACKK :01
     967 .0060 SUNR   :01

   34606 .2131   SREL :03
   34217 .2107 ACKK   :03

   29401 .1810   SUNS :04
    1689 .0104   SUNR :04

    1510 .0093   SUNR :02

      23 .0001 ACKK   :05
      23 .0001   SREL :05

libenet / league of legends protocol success!

Last year I looked into the League of Legends real time protocol, the format of the UDP messages between the game server and clients. My recent lag problems motivated me to look again and I’ve gotten somewhere this time.

The protocol is said to be based on libenet 1.2 with some modifications. The body of the protocol itself is encrypted, presumably to make it harder for third party hacks to sniff data from the game. (It doesn’t make it impossible though, so once again DRM frustrates legit use without dissuading cheaters.) But I don’t care about the body, I just want the enet headers, the sequence numbers and retransmits and stuff. And that’s in the clear!

The best guide I’ve found is this Wireshark dissector, or rather an updated version Boreeas kindly gave me that isn’t checked in anywhere. The key thing is inside the UDP packet, the first 8 bytes are a not-very-interesting header. Then the 9th byte is an Enet command, the 10th byte is a channel number, and the 11th and 12th bytes are the sequence number. (To complicate things sometimes only the first 6 bytes are the header, so the command is the 7th byte, etc.) ACK packets have some bogus sequence number, but the first 2 bytes after that are the sequence number of the packet being acknowledged.

So I put all that together and wrote some Python Impacket code and now I have something printing a summary of UDP captures I made. Below is a few lines from my outputter. This shows the server sending a reliable packet on channel 3 numbered 01a9, then another numbered 01aa, then another number 01ac. My client acknowledges all three. But what happened to 01ab? The server sends that along 200ms later, either because it arrived out of order or else because the server knew to try to send it again. Note that in the meantime 01ad also went missing; that never showed up, so I’m confused. Still, it’s a start. I assume the LoL client shows lag if a reliable packet doesn’t arrive properly.

SREL   03 01a9 00167.521401   00000000: 0D 89 78 BC A7 80 96 CE  86 03 01 A9 00 38 D6 23  ..x..........8.#
  ACKK 03 01a9 00167.521538   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 A9 96 CE        ..m...........
  SUNS 01 0000 00167.542210   00000000: F3 CC 6D 92 A7 03 49 01  00 00 03 8C 00 0A 87 99  ..m...I.........
SREL   03 01aa 00167.562514   00000000: 0D 89 78 BC A7 80 96 E5  86 03 01 AA 00 07 6F 00  ..x...........o.
  ACKK 03 01aa 00167.562663   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 AA 96 E5        ..m...........
  SREL 01 0065 00167.583485   00000000: F3 CC 6D 92 A7 83 8E B4  86 01 00 65 00 1F 6B 4F  ..m........e..kO
SREL   03 01ac 00167.629336   00000000: 0D 89 78 BC A7 80 97 28  86 03 01 AC 00 18 D8 AB  ..x....(........
ACKK   01 0065 00167.629393   00000000: 0D 89 78 BC A7 00 01 01  01 AC 00 65 8E B4        ..x........e..
  ACKK 03 01ac 00167.629477   00000000: F3 CC 6D 92 A7 03 01 03  00 65 01 AC 97 28        ..m......e...(
SUNS   04 0000 00167.688278   00000000: 0D 89 78 BC A7 00 49 04  00 00 03 DD 00 3B BA D6  ..x...I......;..
SREL   03 01ae 00167.688330   00000000: 0D 89 78 BC A7 80 97 64  86 03 01 AE 00 10 F5 54  ..x....d.......T
  ACKK 03 01ae 00167.688425   00000000: F3 CC 6D 92 A7 03 01 03  00 65 01 AE 97 64        ..m......e...d
  SREL 01 0066 00167.709221   00000000: F3 CC 6D 92 A7 83 8F 31  86 01 00 66 00 1F 6B 4F  ..m....1...f..kO
SREL   03 01af 00167.736732   00000000: 0D 89 78 BC A7 80 97 A5  86 03 01 AF 00 44 2B 25  ..x..........D+%
  ACKK 03 01af 00167.736863   00000000: F3 CC 6D 92 A7 03 01 03  00 66 01 AF 97 A5        ..m......f....
ACKK   01 0066 00167.739947   00000000: 0D 89 78 BC A7 00 01 01  01 93 00 66 8F 31        ..x........f.1
  SUNS 01 0000 00167.740008   00000000: F3 CC 6D 92 A7 03 49 01  00 00 03 8F 00 0A 23 68  ..m...I.......#h
SREL   03 01ab 00167.765224   00000000: 0D 89 78 BC A7 80 97 C2  86 03 01 AB 00 1B BC 8D  ..x.............
  ACKK 03 01ab 00167.765389   00000000: F3 CC 6D 92 A7 03 01 03  00 00 01 AB 97 C2 01 03  ..m.............
SUNS   04 0000 00167.770715   00000000: 0D 89 78 BC A7 00 49 04  00 00 03 DF 00 23 31 79  ..x...I......#1y

Here’s a breakdown of packet types from an ARAM game I recorded. 23.77% of packets are from my client to the server, “send unsequenced”. Huh, what does my client have to say to the server that’s so volumnious and yet unimportant? About 41% of traffic is the server sending reliable packets and the client acknowledging them and another 11% is the client sending reliable packets and the server acknowledging them. 21% of the traffic is unsequenced packets from the server, or about the same number of packets as reliable ones. I’d expected more of a bias to unreliable packets from the server than that.

   20086 .2377   SUNS
   17498 .2070   ACKK
   17475 .2068 SREL
   15406 .1823 SUNS
    5670 .0671   SREL
    5101 .0604 ACKK
    1528 .0181 SUNR
    1311 .0155   PING
     203 .0024   SUNR
     197 .0023 PING
      40 .0005 SFRG
       1 .0000 VCON
       1 .0000   CONN

Machine learning: Neural networks introduction

Week four of my Coursera machine learning course was a breezy introduction to neural networks. The lecture videos were very high level but did a good job introducing the concept. The part I hadn’t understood before was how regression techniques are really best suited for linear prediction models, that building Nth order polynomials out of M features leads to O(N*M) work and badness. I also hadn’t really understood that neural networks are just a series of logistic regressions. The input variables are mapped through a logistic model to an intermediate hidden layer (of some chosen number of features), then the hidden layer is mapped again through a second logistic model to yield output variables. However the lecture stopped before we got to backpropagation, so for this week the method of training a neural network is still a mystery.

Logistic regression applied to OCR

The homework is a bit behind and out of sync with the lecture notes. The bulk of the work in the homework was still doing logistic regression, last week’s lecture concept. The hardest part was figuring out how to vectorize the naive loop implementation of the regularized logistic regression cost function we did last week. But I’d already vectorized it so I could just copy my solution from last week, gold star!

The more fun part was actually applying one of these learned models to do something useful with real data; OCR classification of handwritten numbers. The input was 5000 images, 20x20 greyscale pixel arrays, along with their classification (“this squiggle is the number 7”). Our job was to build a multiclass classifier to do the OCR, to predict a digit. So we took the regularized logistic regression cost function we just implemented and used fmincg() to search for the best parameters to match the data. The resulting output vector (theta) is our prediction model. Then we applied that learned model to classify input data. So I’ve now built a linear regression OCR system for handwritten numbers! The final system predicted the input set with 95% accuracy. The final model is quite large; 4010 separate integers. 401 weights for predicting each digit from 0–9, or one weight per pixel plus a constant term. Not exactly parsimony.

One neat thing about multiclass models is they don’t just output a predicted clas (“the number 7”), they also output a vector of probabilities for each possible value: “probability this image is the number 1, probability it is the number 2, ...”. We crush those probabilities down to a single “this input is probably an image of the number 7”. But something to remember for later; machine learning models not only can return a prediction, but a confidence in that prediction. Or some ambiguity, I believe the math works such that a single image might have a 90% probability of being the number 7 and an 80% probability of being the number 9 (for a particularly ambiguous squiggle.)

Neural network forward propagation

The last part of the homework was implementing a basic neural network. Or rather the application of one, the forward propagation that maps the input data through the layers and gives outputs. We were handed parameters that had already been trained, so really this was just an exercise in “can you code up forward propagation?” Useful to do that myself though. In particular I had to puzzle out that the hidden layer consists of 25 nodes. So the final classifier is basically two steps. Logistic regression to map 400 pixels to 25 hidden nodes. And then a second logistic regression to map 25 hidden nodes to 10 probabilities. The central mystery of neural networks is what those “hidden nodes” really mean. And we have Deep Dream to thank for a lovely visualized expression of hidden states in a different kind of machine learning image processing system.

Metacomments

I almost gave up this week. Ran into a bunch of weird technical problems. By far the biggest one was me putting the line “print size(X)” in my code as a debugging aid and then forgetting about it. And suddenly my octave program is complaining about fig2dev missing and I’m down a rabbit hole of Homebrew installs trying to figure out what the hell is wrong. Turns out “print” means print, as in paper, and I needed “printf”. Derp.

I am also doing a lot of stumbling around and shallow learning. Like I know I need to combine the matrix X with the vector theta somehow but forgot which way. Rather than puzzle that out from mathematical principles, I just inspect and see X is 5000x400 and theta is 1x400, and I need to multiply them somehow, so the only sensible math is X*theta’ or theta*X’. So try one out and see if the homework oracle tells me I got the right answer, and call it a day. (Writing this out I realized I picked the wrong one of the two, which is why I keep having to transpose everything. oops.) Anyway this doesn’t feel like learning so much as just bashing about with the only thing that will pass a type checker. I keep telling myself I’m absorbing something though, and my real goal here is just to understand enough about what’s going on that I can use other people’s machine learning systems later.

I do wish the homework assignments had more interactive help. In particular a bit more hand-holding about how to run the code you write, understand what it’s doing, and test it against known good results. In desperation I started looking at the submit.m internals just to see what test cases the homework oracle was using. I don’t get to see the right outputs that way (they’re hidden on the server), but at least I have some reasonable test inputs I can look at.

The only actual course lecture notes are a wiki page. The wiki content is pretty good. But it requires a login to even read the pages! And Coursera’s wiki is broken somehow so you have to log in about once an hour, makes me very cranky.

New LoL NA servers

Riot is finally moving the North American League of Legends game servers from the west coast to somewhere more central, Chicago,. Their network operations guy RiotAhab has been making a series of great posts about netops, his post about the move is good reading. Also buried in the discussion is a comment from dArtaganan, a Riot employee, giving us a new server IP: 104.160.131.1. (Compare old IPs like 192.64.170.78).

A simple ping from my house to the new IP is 70ms. Some random other Chicago IP was about 60ms. Theoretical best RTT (speed of light in copper) is 30ms. Riot is promising ping increases of “up to 30ms” for west coasters, which would put me at 65ms.

That IP is in AS6507. My route to them from my Kansas server (12ms away) ends at be2217.ccr41.ord03.atlas.cogentco.com, which could be a Cogent datacenter like this one. Or maybe Cogent just provides the link and the warehouse is owned by someone else. Note the old west coast IPs are also in that ASN, Riot didn’t set up a new one.

Riot’s ASN has 110 peers, which is impressive; compare 13 for my ISP or 6 for my server. Google has 200+, mega-backbone he.net has nearly 4000. Anyway, Riot’s peering efforts are clearly visible. I imagine each one of those 110 peers is a separately negotiated contract.

Diagnosing a weird LoL lag issue

I’m having a weird lag problem where I get massive packet loss playing LoL. But the reported ping stays low (35ms) and the game is mostly playable. Some small hiccups that look lag related, more than I’m used to, but it’s not hugely awful. Really don’t know what’s going on.

My logs are telling me I’m losing 2.4% of my packets. That seems awfully bad; 0.1% or so is more typical. Borderline surprised it’s playable, but who knows. It’s not clear why the LoL client still reports the 35ms ping; the usual client behavior is if you’re losing packets the reported ping goes up. Or at least it used to be, maybe that changed?

I’ve done every test I can think of to prove that it’s not my home network in general to blame. I can iperf3 burst UDP traffic all day reliably from my house to somebits.com in Kansas. That shares the same route over my ISP as far as cr1-9greatoaks-te-0-7-0-8.bb.spectrumnet.us; then the somebits packets go through he.net on their way to Kansas while the LoL packets go through spectrumnet up to Portland and Riot’s datacenter. That route looks fine, as well as I can test. (with mtr -u, a UDP traceroute).

Confusing things more, a friend of mine also plays on the same ISP in San Francisco. His client is not showing any lag like I am. But we share almost the same route, our routes converge on the fourth hop from 76-14-93-222.sf-cable.astound.net / 76-14-93-218.sf-cable.astound.net onward. So if there were a bad router it’d be close to my house. But then my link to somebits.com goes through that same route and I can test that thoroughly, and it’s showing no problem.

Frankly all signs point to something being wrong with my Mac, the client itself. Only I can reproduce the problem on a second machine, my laptop! Could it be my router? Possibly. But it’s worked fine in the past. I’ll try to test without the router soon.

Here’s some stats from a Wireshark capture I did in an ARAM I just played. I was Amumu.

LoL server address: 192.64.170.78

Wireshark statistics

  • 39750 packets from server, 44769 packets from client
  • 2003 packets reported lost by the client. 2.4% packet loss rate!
  • 39kbps from server, 17kbps from client
  • Average packet size 228 bytes
"Address","Port","Packets","Bytes","Packets A → B","Bytes A → B","Packets B → A","Bytes B → A","Latitude","Longitude"
"192.64.170.78",5107,84517,9616369,39748,6599894,44769,3016475,"-","-"
"192.168.0.20",53040,84517,9616369,44769,3016475,39748,6599894,"-","-"


==================================================================================================================================
Packet Lengths:
Topic / Item       Count         Average       Min val       Max val       Rate (ms)     Percent       Burst rate    Burst start  
----------------------------------------------------------------------------------------------------------------------------------
Packet Lengths     84519         227.56        54            1038          0.0627        100%          0.2400        73.682       
 0-19              0             -             -             -             0.0000        0.00%         -             -            
 20-39             0             -             -             -             0.0000        0.00%         -             -            
 40-79             46272         62.08         54            79            0.0343        54.75%        0.1600        2.285        
 80-159            26150         101.90        80            159           0.0194        30.94%        0.0900        838.818      
 160-319           7204          228.76        160           319           0.0053        8.52%         0.0500        351.673      
 320-639           4120          437.28        320           639           0.0031        4.87%         0.0600        73.648       
 640-1279          773           814.54        640           1038          0.0006        0.91%         0.0600        73.717       
 1280-2559         0             -             -             -             0.0000        0.00%         -             -            
 2560-5119         0             -             -             -             0.0000        0.00%         -             -            
 5120 and greater  0             -             -             -             0.0000        0.00%         -             -            

----------------------------------------------------------------------------------------------------------------------------------


$ sudo mtr -u 192.64.170.78
                                   My traceroute  [v0.85]
ub (0.0.0.0)                                                        Tue Aug  4 17:43:25 2015
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                                    Packets               Pings
 Host                                             Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. router.nelson.monkey.org                       0.0%   981    0.2   0.2   0.2   0.7   0.0
 2. 76-14-35-1.sf-cable.astound.net                0.0%   981    9.8  11.8   4.0 156.4   9.6
 3. 104.220.254.17                                 0.0%   981    7.4   9.2   3.6  31.3   4.0
 4. 76-14-93-218.sf-cable.astound.net              0.0%   981   14.6  17.2   7.7 234.4  22.8
    76-14-93-222.sf-cable.astound.net
 5. cr1-wsache-a-be-100.bb.spectrumnet.us          0.0%   981   11.8  14.2   9.1  37.2   3.8
 6. cr1-55SMarket-te-0-0-0-8.bb.spectrumnet.us     0.0%   981   11.1  14.7  10.3  37.6   4.7
    cr1-55SMarket-te-0-0-0-10.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-9.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-19.bb.spectrumnet.us
    cr1-55SMarket-te-0-0-0-11.bb.spectrumnet.us
 7. cr1-9greatoaks-te-0-7-0-6.bb.spectrumnet.us    0.0%   981   11.5  14.2   8.2  36.4   3.7
    cr1-9greatoaks-te-0-7-0-8.bb.spectrumnet.us
    cr1-9greatoaks-te-0-7-0-9.bb.spectrumnet.us
    cr1-9greatoaks-te-0-7-0-7.bb.spectrumnet.us
 8. cr1-pdx-te-0-0-0-4.bb.spectrumnet.us           0.1%   981   44.3  30.8  23.8  56.2   4.5
    cr1-pdx-te-0-0-0-5.bb.spectrumnet.us
    cr1-pdx-te-0-0-0-6.bb.spectrumnet.us
 9. cr2-fdcp-t4-4.bb.spectrumnet.us                0.0%   981   29.4  34.2  25.2 376.9  25.7
10. 216.243.25.86                                  0.0%   981   28.3  29.9  24.8  51.3   4.0
11. ???

Graph of packets / second

Packets per second

Update

Some updates after a few experiments

  • Problem definitely occurs on two different computers, an iMac and a Macbook Air
  • Problem occurs without my router / switch. Still plugged into my cable modem.
  • I played a game with a friend of mine who happens to also be in San Francisco on the same ISP and plays on a Mac. He had no lag, I did. Here’s my Logs of Lag report and here’s his. I lost 80 packets a minute, he lost 2. WTF? According to traceroute our routes are the same after the 4th hop above, so if it’s a problem in the route it’s something very close to my house at my ISP.
  • However, I can happily shove a huge amount of UDP traffic into my house with no problems. And those packets also traverse that same route to hop 4.
  • I see the same problem on a Windows box in my house. (35 packets lost / minute in a Custom game, which is line with results on the Macs I play on.)

My next step is to try playing through a VPN and see if it helps. I’d also like to understand better what it means for the LoL client to know it’s lost 2.4% of packets and yet still report a low ping. That seems odd; usually the reported ping number goes up in response to retransmits, or at least I thought it did.

Update 2

A friend of mine has a VPS at directspace.net, which is either in the same datacenter as Riot NA or else very nearby. He ran an  iperf2 server for me. Here’s some redacted data testing from my problem network.

iperf shows 69 packets out of 26224 lost, and 47 out of order. that’s about normal for a working link I think, and 1/10th the loss rate I’m seeing from the game.

mtr shows at worst 1 packet dropped out of 100. the stddev to hop 4 is higher than I’d like though.

$ iperf -l 300 -u -t 60 -i 10 -c XXX.XXX.XXX.XXX
------------------------------------------------------------
Client connecting to XXX.XXX.XXX.XXX, UDP port 5001
Sending 300 byte datagrams
UDP buffer size:  208 KByte (default)
------------------------------------------------------------
[  3] local 192.168.0.65 port 34071 connected with XXX.XXX.XXX.XXX port 5001
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 10.0-20.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 20.0-30.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 30.0-40.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 40.0-50.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3] 50.0-60.0 sec  1.25 MBytes  1.05 Mbits/sec
[  3]  0.0-60.0 sec  7.50 MBytes  1.05 Mbits/sec
[  3] Sent 26225 datagrams
[  3] Server Report:
[  3]  0.0-60.0 sec  7.48 MBytes  1.05 Mbits/sec   1.561 ms   69/26224 (0.26%)
[  3]  0.0-60.0 sec  47 datagrams received out-of-order

$ mtr --report -c 100 -u XXX.XXX.XXX.XXX
Start: Wed Aug  5 21:37:40 2015
HOST: ub                          Loss%   Snt   Last   Avg  Best  Wrst StDev
  1.|-- router                     0.0%   100    0.2   0.2   0.2   0.5   0.0
  2.|-- 76-14-35-1.sf-cable.astou  1.0%   100    9.3  11.0   5.4  57.1   7.2
  3.|-- 104.220.254.17             0.0%   100    9.9   9.4   5.0  28.1   4.1
  4.|-- 76-14-93-222.sf-cable.ast  0.0%   100   14.5  15.0   9.9 114.6  11.0
  5.|-- cr1-wsache-a-be-100.bb.sp  0.0%   100   11.9  14.9  10.2  33.2   3.7
  6.|-- cr1-55SMarket-te-0-0-0-8.  0.0%   100   11.9  13.4  10.4  32.0   2.3
  7.|-- cr1-9greatoaks-te-0-7-0-8  0.0%   100   14.6  15.1  10.3  33.1   4.6
  8.|-- cr1-pdx-te-0-0-0-4.bb.spe  0.0%   100   26.6  29.8  26.2  47.5   3.9
  9.|-- cr2-pdx-te-0-1-0-4.bb.spe  0.0%   100   29.7  29.6  26.1  47.8   3.3
 10.|-- directspace.nwax.net       1.0%   100   29.9  31.8  26.0 166.0  15.4
 11.|-- 69-163-34-113.in-addr.arp  0.0%   100   28.1  28.8  25.2  31.4   1.2
 12.|-- XXX.XXX.XXX.XXX            0.0%   100   28.6  29.3  26.1  47.0   2.7

Update 3: I have a theory: out of order packets. My mtr tests are telling me there’s something a bit flaky between hops 3 to 4. Occasionally a packet will take a very long time, like 200ms, and the stddev on that hop is way higher than the others. I wonder if an out of order packet causes the LoL client to drop it or otherwise treat it as a lost packet? To further complicate things, mtr -u shows me that there are many different paths on my route. All the same lengths, but node 4 (the suspect one) has a couple of different IP addresses that show up. If only one path is congested that will cause a lot of out of order packets.

I don’t know what LoL does with out of order packets. ENet, the protocol LoL is based on, is pretty clear about what it does:

ENet provides sequencing for all packets by assigning to each sent packet a sequence number that is incremented as packets are sent. ENet guarantees that no packet with a higher sequence number will be delivered before a packet with a lower sequence number, thus ensuring packets are delivered exactly in the order they are sent.

For unreliable packets, ENet will simply discard the lower sequence number packet if a packet with a higher sequence number has already been delivered. This allows the packets to be dispatched immediately as they arrive, and reduce latency of unreliable packets to an absolute minimum. For reliable packets, if a higher sequence number packet arrives, but the preceding packets in the sequence have not yet arrived, ENet will stall delivery of the higher sequence number packets until its predecessors have arrived.

But I don’t know how LoL uses these features, in particular what packets are marked reliable / unreliable.

The good thing about this theory is it explains a lot of the facts I see, including why my friend at the same ISP doesn’t have the same lag. (He’s beyond hop 4!). The bad thing about this theory is I still can’t really reproduce the presumed failure with iperf. iperf3 does report out of order packets (as an error message!) but I’ve only been able to induce it to do that with ridiculously high bandwidth tests, and even then not reliably. But maybe iperf3 is really polite and sends packets spaced exactly N ms apart so is less likely to have an ordering problem?

Here’s an ICMP traceroute showing the high stddev at node 4.

$ mtr -n somebits.com

                             My traceroute  [v0.85]
ub (0.0.0.0)                                           Wed Aug  5 23:03:04 2015
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                       Packets               Pings
 Host                                Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 192.168.0.1                       0.0%   539    0.3   0.3   0.2  29.1   1.2
 2. 76.14.35.1                        0.4%   539    8.0  11.0   4.7  60.6   7.7
 3. 104.220.254.17                    0.0%   539    8.0   9.6   5.5  30.4   4.7
 4. 76.14.93.222                      0.6%   539   13.5  17.0   9.7 229.9  22.1
 5. 208.76.187.33                     0.0%   539   28.9  14.1  10.2  36.7   4.1
 6. 208.76.185.26                     0.0%   538   12.8  14.6   9.0  35.5   4.8
 7. 208.76.185.58                     0.0%   538   13.6  14.0  10.0  36.8   3.7
 8. 206.223.116.37                    0.0%   538   14.7  16.5   8.5  44.6   5.6
 9. 184.105.213.106                   0.0%   538   38.3  44.2  37.0  74.5   5.9
10. 184.105.222.22                    0.2%   538   91.2  82.6  62.7 121.7  14.5
11. 184.105.213.37                    0.0%   538   71.1  69.6  62.9  96.7   5.8
12. 216.66.78.90                      0.2%   538   56.5  56.6  48.1  83.5   6.2
13. 69.30.209.138                     0.0%   538   49.6  54.4  47.9  83.6   6.1
14. 192.187.107.5                     0.0%   538   53.4  54.9  48.2  87.9   5.4
15. 107.150.51.74                     0.0%   538   51.3  52.1  47.4  96.1   4.8

Update 4: A VPN fixes my problem! I sort of predicted it would, glad to confirm my hunch and also nice to have a workaround until the real problem is fixed. I set up a TCP VPN through Cloak, promised to US West Coast. I ended up going through Seattle. The resulting log shows a little more latency than without the VPN but also nearly no packet loss. Yay!

I set up Cloak because they have a really great Mac client, easy to get going. If I make a habit of this I may consider a VPN endpoint I own up in Seattle / Portland. Would rather just fix my ISP problem though. Don’t want to be paying $10 a month just to fix someone else’s broken service.

Update 5: this problem went away, and I don’t know why. I’m now playing games with 0.2 packets / s, very good, and no obvious lag. It may have been fixed by the Riot server move to Chicago, that’s the most likely explanation. But I’m still struck by the way I was getting this lag and my friend playing the same game with me on the same ISP wasn’t! That fourth hop from me is still showing suspiciously high standard deviation, so whatever that means it may well be unrelated.

iperf to measure UDP loss

Sometimes I want to test link quality by seeing if UDP packets are getting lost. iPerf is a nice tool for that. It’s a client + server command line app that generates floods of packets and verifies they arrived on the other end. A bandwidth intensive ping.

To confuse things, there’s an iperf2 and an iperf3. They sort of do similar things but I think iperf3 is mostly better. In particular the server is now mostly a dumb packet reflector and the client can give the server instructions like “try UDP now” etc, more suited for running a server somewhere stable and headless and testing with the client. See in particular the -R option to ask the server to send packets to the client.

server$ iperf3 -s

client$ iperf3 -u -c somebits.com
Connecting to host somebits.com, port 5201
[  5] local 192.168.0.23 port 63531 connected to 107.150.51.74 port 5201
[ ID] Interval           Transfer     Bandwidth       Total Datagrams
[  5]   0.00-1.00   sec   120 KBytes   983 Kbits/sec  15
[  5]   1.00-2.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   2.00-3.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   3.00-4.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   4.00-5.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   5.00-6.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   6.00-7.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   7.00-8.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   8.00-9.00   sec   128 KBytes  1.05 Mbits/sec  16
[  5]   9.00-10.00  sec   128 KBytes  1.05 Mbits/sec  16
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Jitter    Lost/Total Datagrams
[  5]   0.00-10.00  sec  1.24 MBytes  1.04 Mbits/sec  1.545 ms  1/159 (0.63%)
[  5] Sent 159 datagrams

iperf Done.

If I understand correctly the default UDP settings try to send 1 megabit a second worth of packets. That works out to 128 KBytes each second in 16 datagrams, or 8192 byte UDP datagrams. With the usual 1500 byte MTU that works out to 6 actual packets. You can set options for bandwidth, maximum datagram size, etc. Here’s a nice long test sending 1400 byte packets.

iperf3 -R -l 1400 -l 1000 -t 100 -u -c somebits.com

There’s a few public iperf servers to test against. The one run by @scottlinux in California was working well when I just tried it.

Machine learning: Logistic regression

Just finished week 3 of Andrew Ng’s machine learning course on Coursera. I’m going to try to blog each week summarizing what I learned.

This week’s topic is logistic regression; predicting discrete outcomes like “success or failure” from numeric data inputs. Ie: “our diagnostics measure these 4 numbers for a tumor. Is it cancerous or benign?” Turns out logistic regression is basically just linear regression where the output set is restricted to the interval [0, 1]. Normal linear regression gives all real numbers on output, so you pass that through the sigmoid curve to bound the result to [0, 1]. That number is effectively “the probability the output is 0”, you can then threshold it at 0.5 to map it to a strictly binary “success or failure” output. There’s a bunch of math then to define the cost function and the partial derivatives of the cost function which you can then use with an optimization algorithm like gradient descent.

Logistic regression only classifies data into two classes. If you want N classes you do logistic prediction many times, ie: “is it A or not A? is it B or not B? is it C or not C?” and then pick the class ABC with the highest probability.

The predictor you get from the logistic regression is best understood in terms of a decision boundary, a drawing of the threshold that tips an input from success to failure. My final homework assignment was learning this threshold boundary to separate plusses from squares where the input data is 2 dimensional. The green line is the learned threshold boundary, some sixth order polynomial the magic optimizer found for me.

Screen Shot 2015-08-02 at 11.02.08 AM

Thankfully the course moved on a bit from math into “use the black box” by introducing fminunc, a black-box minimizer provided by Matlab/Octave. All it needs is the cost function and its partial derivatives and it does who-knows-what to find the minimum. Frankly I wish the class spent more time on how to use fminunc well and less time deriving the gradient descent solutions that I’ll never use again. But gradient descent is a nice simple optimizer and it is good to know how at least one works.

This week also introduced the concept of overfitting, of specializing your predictor too tightly to the data. Regularization was the solution provided for overfitting; basically biasing the cost function to prefer small values of theta, the learning model parameters we’re optimizing. Ng doesn’t really explain why small values of theta are “better” other than presenting some intuition that a theta_i of 0 means the parameter is fully ignored and a theta_i of 1000 means it’s way too overemphasized. The regularization parameter lambda is picked out of a hat much like the learning rate alpha is also picked for gradient descent.

Along the way I learned how to define anonymous functions in Octave which then gives you a really easy way to curry a partial function application (in this case, currying X and y into my costFunction so that fminunc only works on the parameter t.

fminunc(@(t)(costFunction(t, X, y)), initial_theta, options)

I continue to be amazed that I type vector equations into Octave and they Just Work on first try, despite my being rusty on linear algebra not to mention matrix programming languages. I’m kind of just accepting that if the homework grader says I got it right I’m done.

Some metacomments about the course... I read something somewhere that characterized this as an advanced undergraduate class, maybe sophomore or junior level. That feels about right and explains why it seems a little too easy. But easy in the right ways for me, I really don’t want to do the math derivations. Also I discovered a lot of previous students’ homework checked in on GitHub. Cheating would be stupid, who would I cheat but myself? But it’s nice to be able to look what other students did. Helped me verify arrayfun() was really the right thing to apply a scalar function to a matrix, for instance.

Now I feel like I’ve studied enough machine learning to apply it to a problem I care about. I intend to look at League of Legends match results, to see whether I can predict a game is a win or a loss based on match performance. The simplest thing is to look at end of game stats like kills or gold earned. Of course end of game I already know for sure if it was a win or a loss, but I’m thinking I can read the learned model parameters out to see how significant a contribution those inputs like kills are to whether a team wins. Alternately I can get ahold of some mid-game stats like “gold earned after 20 minutes”, whether that results in a win or a loss is a bit more of a legitimate prediction problem.

Python looping for n times

A Twitter friend proposed an idiom for doing something N times in Python I hadn’t seen before, Using itertools.repeat instead of range. I was curious if it was better.

$ python3 -V
Python 3.4.3
$ python2 -V
Python 2.7.10

$ python3 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 275 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 133 usec per loop
$ python3 -m timeit 'for _ in itertools.repeat(1, 10000): pass'
10000 loops, best of 3: 130 usec per loop

$ python2 -m timeit 'for _ in range(10000): pass'
1000 loops, best of 3: 218 usec per loop
$ python2 -m timeit 'for _ in xrange(10000): pass'
1000 loops, best of 3: 179 usec per loop
$ python2 -m timeit 'for _ in itertools.repeat(None, 10000): pass'
10000 loops, best of 3: 122 usec per loop

So huh, itertools.repeat is about 50% the cost of using range. We’re only talking 13ns per iteration, or roughly 50 CPU cycles. If you’re doing meaningful work in that loop it won’t matter. Still it’s neat that itertools.repeat is more efficient. Perhaps this shouldn’t surprise me, it doesn’t have to do the work of generating increasing integers. But I’d assumed no one had optimized itertools this carefully.

Note that in Python3 range is an actual type and doesn’t create a list, tuple, iterator, or generator. Also interesting that repeating an integer is 3% more efficient than repeating None; that’s a reproducible result.

Python2 is faster across the board. I see that a lot in Python and it makes me wonder. But the itertools vs. range/xrange difference is still about 50%, or meaningful.

Having now understood all this I’ll go right back to using range() like my grandpappy did.

MacOS directory permissions

Macs have this weird problem where the Unix file permissions for things get corrupted. Not just a couple of top level directories either. Things like the Finnish localization file for iBooks, an app I have literally never run, is marked group writeable and shouldn’t be. How does this happen?

The thing that’s most alarming is my root directory, /, is mode 0777. World writeable. And owned by my user account, not root. Literally any program running on my computer can come in and hijack the whole system because of that. Not the first time that’s happened either. I’ve read somewhere that a bunch of bad Mac install scripts like to just recursively make things world writeable “to make it work” and they work their way up to /. Also there was that one time when iTunes kept making /Users world writeable. Quality programming there, Apple.

The problem is so common Disk Utility has a special GUI app just to “repair permissions” by comparing the filesystem to records of what should be there left behind by installers. Only that’s a little scary because what if it breaks something? Helpfully there’s an audit mode just to see what’s changed. Run from the GUI or via diskutil verifyPermissions /.

At the bottom of the page is the audit of what all the tool finds wrong on my Mac after filtering out 3000+ lines of iBooks.app garbage. Mostly not too scary, although libruby.dylib being world writeable sure seems like a potential security disaster. The most terrifying one is

Warning: SUID file “System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent” has been modified and will not be repaired

What, a setuid root executable that’s part of a remote management system that’s been modified? Why that’s not suspicious at all! But have no fear: Apple itself says that’s one of roughly 100 messages from the audit you can “safely ignore”. So yes, the security audit tool prints a lot of false positives. Fucking garbage.

Note that the root directory is not one of the reports in the audit.

I felt lucky and ran the tool and it changed a bunch of things. Then ran the audit again and it found three problems, including the setuid root file I’m supposed to ignore.

It did not repair my root directory. I manually set that to 0755, owned by root.wheel.

Started verify/repair permissions on disk0s2 Macintosh HD
Permissions differ on "System/Library/CoreServices/Feedback Assistant.app"; should be drwxr-xr-x ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Warning: SUID file "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent" has been modified and will not be repaired
Permissions differ on "Applications/Safari.app/Contents/Resources/Safari.help/Contents/Resources/index.html"; should be lrwxr-xr-x ; they are -rw-r--r-- 
Group differs on "Library/Printers"; should be 80; group is 0
Group differs on "Library/Printers/Icons"; should be 80; group is 0
Group differs on "Library/Printers/InstalledPrinters.plist"; should be 80; group is 0
Permissions differ on "Library/Printers/InstalledPrinters.plist"; should be -rw-rw-rw- ; they are -rw-r--r-- 
Group differs on "Library/Java"; should be 0; group is 80
Permissions differ on "Library/Java"; should be drwxr-xr-x ; they are drwxrwxr-x 
Group differs on "Library/Preferences/SystemConfiguration/com.apple.Boot.plist"; should be 80; group is 0
Group differs on "Library/Preferences/com.apple.alf.plist"; should be 80; group is 0
Group differs on "Library/Printers/PPDs"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents/Resources"; should be 80; group is 0
Permissions differ on "System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Group differs on "private/var/db/GPURestartReporter"; should be 0; group is 80
Permissions differ on "private/var/db/GPURestartReporter"; should be drwxr-xr-x ; they are drwxrwx--- 
Finished verify/repair permissions on disk0s2 Macintosh HD